Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move SEO Fields logic to seprate FIeld instances
Pacu212401455364b
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex d85f5e3c91..e8c0fdbe60 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -136,14 +136,3 @@ def create_superuser(credentials):else:msg = 'Superuser already exists - %(email)s' % credentialsreturn msg---def merge_dicts(*dict_args):- """Workaround for Python3.4 to merge two dicts within one line of code.- Given any number of dicts, shallow copy and merge into a new dict,- precedence goes to key value pairs in latter dicts.- """- result = {}- for dictionary in dict_args:- result.update(dictionary)- return resultdiff --git a/saleor/dashboard/category/forms.py b/saleor/dashboard/category/forms.pyindex 6ad68972cd..d7e0785b38 100644--- a/saleor/dashboard/category/forms.py+++ b/saleor/dashboard/category/forms.py@@ -4,35 +4,25 @@ from django.utils.text import slugifyfrom django.utils.translation import pgettext_lazyfrom text_unidecode import unidecode-from ...core.utils import merge_dictsfrom ...product.models import Category-from ..seo.utils import (- MIN_DESCRIPTION_LENGTH, MIN_TITLE_LENGTH, SEO_HELP_TEXTS, SEO_LABELS,- SEO_WIDGETS)+from ..seo.fields import SeoDescriptionField, SeoTitleFieldclass CategoryForm(forms.ModelForm):def __init__(self, *args, **kwargs):self.parent_pk = kwargs.pop('parent_pk')super().__init__(*args, **kwargs)- self.fields['seo_description'].widget.attrs.update({- 'data-bind': self['description'].auto_id,- 'min-recommended-length': MIN_DESCRIPTION_LENGTH})- self.fields['seo_title'].widget.attrs.update({- 'data-bind': self['name'].auto_id,- 'min-recommended-length': MIN_TITLE_LENGTH})+ self.fields['seo_description'] = SeoDescriptionField(+ extra_attrs={'data-bind': self['description'].auto_id})+ self.fields['seo_title'] = SeoTitleField(+ extra_attrs={'data-bind': self['name'].auto_id})class Meta:model = Categoryexclude = ['slug']- labels = merge_dicts(- {- 'name': pgettext_lazy('Item name', 'Name'),- 'description': pgettext_lazy('Description', 'Description')- },- SEO_LABELS)- help_texts = SEO_HELP_TEXTS- widgets = SEO_WIDGETS+ labels = {+ 'name': pgettext_lazy('Item name', 'Name'),+ 'description': pgettext_lazy('Description', 'Description')}def save(self, commit=True):self.instance.slug = slugify(unidecode(self.instance.name))diff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.pyindex 7d7c8cc6eb..da850f3e4f 100644--- a/saleor/dashboard/collection/forms.py+++ b/saleor/dashboard/collection/forms.py@@ -4,12 +4,9 @@ from django.utils.text import slugifyfrom django.utils.translation import pgettext_lazyfrom text_unidecode import unidecode-from ...core.utils import merge_dictsfrom ...product.models import Collection, Productfrom ..forms import AjaxSelect2MultipleChoiceField-from ..seo.utils import (- MIN_DESCRIPTION_LENGTH, MIN_TITLE_LENGTH, SEO_HELP_TEXTS, SEO_LABELS,- SEO_WIDGETS)+from ..seo.fields import SeoDescriptionField, SeoTitleFieldclass CollectionForm(forms.ModelForm):@@ -20,27 +17,20 @@ class CollectionForm(forms.ModelForm):class Meta:model = Collectionexclude = ['slug']- labels = merge_dicts(- {- 'name': pgettext_lazy('Item name', 'Name'),- 'products': pgettext_lazy('Products selection', 'Products'),- 'background_image': pgettext_lazy(- 'Products selection',- 'Background Image')- },- SEO_LABELS)- widgets = SEO_WIDGETS- help_texts = SEO_HELP_TEXTS+ labels = {+ 'name': pgettext_lazy('Item name', 'Name'),+ 'products': pgettext_lazy('Products selection', 'Products'),+ 'background_image': pgettext_lazy(+ 'Products selection',+ 'Background Image')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)if self.instance.pk:self.fields['products'].set_initial(self.instance.products.all())- self.fields['seo_description'].widget.attrs.update({- 'min-recommended-length': MIN_DESCRIPTION_LENGTH})- self.fields['seo_title'].widget.attrs.update({- 'data-bind': self['name'].auto_id,- 'min-recommended-length': MIN_TITLE_LENGTH})+ self.fields['seo_description'] = SeoDescriptionField()+ self.fields['seo_title'] = SeoTitleField(+ extra_attrs={'data-bind': self['name'].auto_id})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.pyindex 3b1da816ae..a9d5a2f9ce 100644--- a/saleor/dashboard/page/forms.py+++ b/saleor/dashboard/page/forms.py@@ -1,45 +1,35 @@from django import formsfrom django.utils.translation import pgettext_lazy-from ...core.utils import merge_dictsfrom ...page.models import Pagefrom ..product.forms import RichTextField-from ..seo.utils import (- MIN_DESCRIPTION_LENGTH, MIN_TITLE_LENGTH, SEO_HELP_TEXTS, SEO_LABELS,- SEO_WIDGETS, prepare_seo_description)+from ..seo.fields import SeoDescriptionField, SeoTitleField+from ..seo.utils import prepare_seo_descriptionclass PageForm(forms.ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- self.fields['seo_description'].widget.attrs.update({- 'data-bind': self['content'].auto_id,- 'data-materialize': self['content'].html_name,- 'min-recommended-length': MIN_DESCRIPTION_LENGTH})- self.fields['seo_title'].widget.attrs.update({- 'data-bind': self['title'].auto_id,- 'min-recommended-length': MIN_TITLE_LENGTH})+ self.fields['seo_description'] = SeoDescriptionField(+ extra_attrs={+ 'data-bind': self['content'].auto_id,+ 'data-materialize': self['content'].html_name})+ self.fields['seo_title'] = SeoTitleField(+ extra_attrs={'data-bind': self['title'].auto_id})class Meta:model = Pageexclude = []- widgets = merge_dicts(- {'slug': forms.TextInput(attrs={'placeholder': 'example-slug'})},- SEO_WIDGETS)- labels = merge_dicts(- {- 'is_visible': pgettext_lazy(- 'Visibility status indicator', 'Publish')- },- SEO_LABELS)- help_texts = merge_dicts(- {- 'slug': pgettext_lazy(- 'Form field help text',- 'Slug is being used to create page URL')- },- SEO_HELP_TEXTS)+ widgets = {+ 'slug': forms.TextInput(attrs={'placeholder': 'example-slug'})},+ labels = {+ 'is_visible': pgettext_lazy(+ 'Visibility status indicator', 'Publish')},+ help_texts = {+ 'slug': pgettext_lazy(+ 'Form field help text',+ 'Slug is being used to create page URL')}content = RichTextField()diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex f5ed1a26d1..899a1de89e 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -10,15 +10,13 @@ from django.utils.translation import pgettext_lazyfrom mptt.forms import TreeNodeChoiceFieldfrom . import ProductBulkAction-from ...core.utils import merge_dictsfrom ...product.models import (AttributeChoiceValue, Category, Collection, Product, ProductAttribute,ProductImage, ProductType, ProductVariant, Stock, StockLocation,VariantImage)from ..forms import OrderedModelMultipleChoiceField, ModelChoiceOrCreationField-from ..seo.utils import (- MIN_DESCRIPTION_LENGTH, MIN_TITLE_LENGTH, SEO_HELP_TEXTS, SEO_LABELS,- SEO_WIDGETS, prepare_seo_description)+from ..seo.fields import SeoDescriptionField, SeoTitleField+from ..seo.utils import prepare_seo_descriptionfrom ..widgets import RichTextEditorWidgetfrom .widgets import ImagePreviewWidget@@ -190,27 +188,22 @@ class ProductForm(forms.ModelForm, AttributesMixin):class Meta:model = Productexclude = ['attributes', 'product_type', 'updated_at']- labels = merge_dicts(- {- '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(- 'Availability date', 'Availability date'),- 'is_published': pgettext_lazy(- 'Product published toggle', 'Published'),- 'is_featured': pgettext_lazy(- 'Featured product toggle',- 'Feature this product on homepage'),- 'collections': pgettext_lazy(- 'Add to collection select', 'Collections'),- },- SEO_LABELS)- help_texts = SEO_HELP_TEXTS- widgets = SEO_WIDGETS+ 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(+ 'Availability date', 'Availability date'),+ 'is_published': pgettext_lazy(+ 'Product published toggle', 'Published'),+ 'is_featured': pgettext_lazy(+ 'Featured product toggle',+ 'Feature this product on homepage'),+ 'collections': pgettext_lazy(+ 'Add to collection select', 'Collections')}category = TreeNodeChoiceField(queryset=Category.objects.all())collections = forms.ModelMultipleChoiceField(@@ -227,13 +220,12 @@ class ProductForm(forms.ModelForm, AttributesMixin):self.prepare_fields_for_attributes()self.fields['collections'].initial = Collection.objects.filter(products__name=self.instance)- self.fields['seo_description'].widget.attrs.update({- 'data-bind': self['description'].auto_id,- 'data-materialize': self['description'].html_name,- 'min-recommended-length': MIN_DESCRIPTION_LENGTH})- self.fields['seo_title'].widget.attrs.update({- 'data-bind': self['name'].auto_id,- 'min-recommended-length': MIN_TITLE_LENGTH})+ self.fields['seo_description'] = SeoDescriptionField(+ extra_attrs={+ 'data-bind': self['description'].auto_id,+ 'data-materialize': self['description'].html_name})+ self.fields['seo_title'] = SeoTitleField(+ extra_attrs={'data-bind': self['name'].auto_id})def clean_seo_description(self):seo_description = prepare_seo_description(diff --git a/saleor/dashboard/seo/fields.py b/saleor/dashboard/seo/fields.pynew file mode 100644index 0000000000..aa8cc98eb3--- /dev/null+++ b/saleor/dashboard/seo/fields.py@@ -0,0 +1,51 @@+from django import forms+from django.utils.translation import pgettext_lazy++from ...seo.models import SeoModel+from ..widgets import CharsLeftWidget++SEO_FIELD_HELP_TEXT = pgettext_lazy(+ 'Form field help text',+ 'If empty, the preview shows what will be autogenerated.')+MIN_DESCRIPTION_LENGTH = 120+MIN_TITLE_LENGTH = 25+DESCRIPTION_MAX_LENGTH = SeoModel._meta.get_field('seo_description').max_length+TITLE_MAX_LENGTH = SeoModel._meta.get_field('seo_title').max_length+++class SeoTitleField(forms.CharField):+ help_text = SEO_FIELD_HELP_TEXT+ label = pgettext_lazy(+ (+ 'Field name, ',+ 'Title that will be used to describe page in Search Engines'),+ 'SEO Title')+ widget = CharsLeftWidget(+ attrs={+ 'data-min-recommended-length': MIN_TITLE_LENGTH,+ 'maxlength': TITLE_MAX_LENGTH})++ def __init__(self, extra_attrs=None, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.max_length = TITLE_MAX_LENGTH+ if extra_attrs:+ self.widget.attrs.update(extra_attrs)+++class SeoDescriptionField(forms.CharField):+ help_text = SEO_FIELD_HELP_TEXT+ label = pgettext_lazy(+ (+ 'Field name, Meta Description is page summary '+ 'used by Search Engines'),+ 'Meta Description'),+ widget = CharsLeftWidget(+ attrs={+ 'data-min-recommended-length': MIN_DESCRIPTION_LENGTH,+ 'maxlength': DESCRIPTION_MAX_LENGTH})++ def __init__(self, extra_attrs=None, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.max_length = DESCRIPTION_MAX_LENGTH+ if extra_attrs:+ self.widget.attrs.update(extra_attrs)diff --git a/saleor/static/dashboard/js/components/google-preview.js b/saleor/static/dashboard/js/components/google-preview.jsindex 17b142b975..277b29bd1d 100644--- a/saleor/static/dashboard/js/components/google-preview.js+++ b/saleor/static/dashboard/js/components/google-preview.js@@ -37,7 +37,7 @@ function updateCharsCount(seoField) {if (!$fieldLength && seoField.attr('placeholder')) {$fieldLength = seoField.attr('placeholder').length;}- const $minRecommendedLength = seoField.attr('min-recommended-length');+ const $minRecommendedLength = seoField.data('min-recommended-length');const $charCountWrapper = $charCount.parent();if ($fieldLength < $minRecommendedLength) {$charCountWrapper.addClass('orange-text');diff --git a/tests/test_core.py b/tests/test_core.pyindex facc779b85..3b4a9f6bfe 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -7,7 +7,7 @@ from prices import Moneyfrom saleor.account.models import Address, Userfrom saleor.core.utils import (Country, create_superuser, format_money, get_country_by_ip,- get_currency_for_country, merge_dicts, random_data)+ get_currency_for_country, random_data)from saleor.core.utils.text import get_cleaner, strip_htmlfrom saleor.discount.models import Sale, Voucherfrom saleor.order.models import Order@@ -184,19 +184,3 @@ def test_utils_strip_html():'\t<b>World</b>')text = strip_html(base_text, strip_whitespace=True)assert text == 'Hello World'--- 'first_dict, second_dict',- (- ({}, {}),- ({}, {'foo': 'bar'}),- ({'foo': 'bar'}, {'bar': 'foo'}), # Regular case- ({'foo': 'bar'}, {}),- ({'foo': 'bar'}, {'foo': 'bar'}))) # Merge two same dicts-def test_merge_dicts(first_dict, second_dict):- result = merge_dicts(first_dict, second_dict)- expected_result = {}- expected_result.update(first_dict)- expected_result.update(second_dict)- assert result.items() == expected_result.items()