From 6644d46f7549702a3e6f6a651d399addbfeac255 Mon Sep 17 00:00:00 2001 From: Diego Calvo Date: Mon, 31 Jan 2022 12:34:13 +0100 Subject: [PATCH] popular categories --- products/admin.py | 2 +- products/forms.py | 2 +- products/models.py | 6 ++++++ products/views.py | 8 ++++---- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/products/admin.py b/products/admin.py index edb53a8..c89f706 100644 --- a/products/admin.py +++ b/products/admin.py @@ -26,7 +26,7 @@ class ProductAdmin(admin.ModelAdmin): class CategoryTagAdmin(TagModelAdmin): form = forms.CategoryTagForm - list_display = ('label', 'name', 'official') + list_display = ('label', 'name', 'official', 'level') search_fields = ('label', 'name', 'slug') diff --git a/products/forms.py b/products/forms.py index 4610b7d..a978388 100644 --- a/products/forms.py +++ b/products/forms.py @@ -19,7 +19,7 @@ class CategoryTagForm(forms.ModelForm): parent_category = autocomplete.Select2ListCreateChoiceField(required=False, widget=autocomplete.Select2(url='category-tag-autocomplete', attrs={"data-tags": "true"})) class Meta: model = CategoryTag - fields = ('name', 'label', 'slug', 'parent_category', 'official') + fields = ('name', 'label', 'slug', 'parent_category', 'official', 'image') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) diff --git a/products/models.py b/products/models.py index 77ede37..bc70fe3 100644 --- a/products/models.py +++ b/products/models.py @@ -6,6 +6,11 @@ from companies.models import Company # Create your models here. +def categoryimage_path(instance, filename): + """Add the instance's id to the path + """ + return f"category/{instance.id}/{filename}" + class TreeTag(TagTreeModel): class TagMeta: initial = "" @@ -17,6 +22,7 @@ class TreeTag(TagTreeModel): class CategoryTag(TagTreeModel): official = models.BooleanField('Oficial', default=False) + image = models.ImageField('Imagen de la categoría', upload_to='categories/', null=True, blank=True) class TagMeta: initial = "" force_lowercase = False diff --git a/products/views.py b/products/views.py index 788329d..efcee81 100644 --- a/products/views.py +++ b/products/views.py @@ -121,16 +121,16 @@ def get_latest_companies(number): return result def get_popular_categories(number): - categories_list = list(CategoryTag.objects.filter(level=1, official=True).values_list('name', flat=True)) + categories_list = list(CategoryTag.objects.filter(level=1, official=True).values('name', 'image')) counted_categories = [] for cat in categories_list: count = 0 - categories = get_category_and_descendants(cat) + categories = get_category_and_descendants(cat['name']) for i in categories: count += i.count counted_categories.append({ - "name": cat, - "image": None, + "name": cat['name'], + "image": cat['image'], "count": count }) popular = sorted(counted_categories, key=lambda d: d['count'], reverse=True)[:number]