12

I have problem with show product in category. (Products are show but when i click on category (tshirt) i have this problem AttributeError at /man/tshirt/ 'QuerySet' object has no attribute 'objects

views.py

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(section='man', available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.objects.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products})

urls.py

 urlpatterns = [
    url(r'^$', views.main, name='main'),
    url(r'^man/$', views.product_list, name='product_list'),
    url(r'^man/(?P<category_slug>[-\w]+)/$',
        views.product_list,
        name='product_list_by_category'),


]

models.py

class Category(models.Model):
    name = models.CharField(max_length=200,
                            db_index=True)
    slug = models.SlugField(max_length=200,
                            db_index=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

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

list.html

{% extends "shop/base.html" %}
{% load static %}

{% block title %}VPW{% endblock %}

{% block content %}
<ul>
    {% for c in categories %}
    <li>
        <a href="{{ c.get_absolute_url }}">{{c.name}}</a>
    </li>
    {% endfor %}
</ul>

    {% for product in products %}
     {{ product.name }}
    {% endfor %}
{% endblock %}

1 Answer 1

25

You should change

products = products.objects.filter(category=category)

to

products = products.filter(category=category)

In short, you've already queried data at the objects level, thus the .objects identifier is no longer necessary or valid at this point in the code.

You can find more info here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.