W
W
WITT2021-09-06 23:32:41
Django
WITT, 2021-09-06 23:32:41

How to display both the elements of this category and the elements of all its subcategories when selecting a category?

I'm new to django, and to python too, now I'm practicing creating an online store and sent before the problem that it would be logical when choosing a category to also display products from all its subcategories. Google, unfortunately, did not help ... I think that you need to somehow filter the product correctly in the views, but how? skills are not enough to understand. Using Django-mptt for category tree (fewer db queries)

models.py

class Category(MPTTModel):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

    class Meta:
        ordering = ('name',)
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

    def get_absolute_url(self):
        return reverse('shop:product_list_by_category',
                        args=[self.slug])


    def __str__(self):
        return self.name


views.py
def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True).order_by('-created')
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
    return render(request,
                  'shop/shop.html',
                  {'category': category,
                  'categories': categories,
                   'products': products})


html
<div class="category_conteiner">
    {% recursetree categories %}
        <div class="sub_menu_category">
            <a href="{{ node.get_absolute_url }}" class="subcatbtn">{{ node.name }}</a>
            {% if not node.is_leaf_node %}
            <div class="subcat_content">
                <div class="subcat_column">
                    {{ children }}
                </div>
            </div>
            {% endif %}
        </div> 
    {% endrecursetree %}


Now the sorting of products is obtained only by the category that was selected when adding the product

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bbquite, 2021-09-06
@WebDev921

<ul class="root">
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

doka

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question