视图/模板在Django中返回不正确的信息

时间:2018-01-31 01:22:32

标签: python django django-templates django-views

我有一个视图,它返回所有产品,而不仅仅是过滤产品。即使我删除了最后一行products =,模板仍会呈现所有数据库对象。

class ProductListView(ListView):
    context_object_name = 'products'
    model = models.Product
    template_name = "catalogue/catalogue.html"
    products = Product.objects.filter(category__name="sundries")

这是我的模板逻辑:

                {% for product in products %}
                <tr>   
                    <td><h5>{{ product.name }}</h5>
                    <p>Cooked with chicken and mutton cumin spices</p></td>
                    <td><p><strong>£ {{ product.price }}</strong></p></td>
                    <td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td>
                </tr>
                {% endfor %} 

和Models.py

lass Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=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])

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products')
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-created',)
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.name

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

2 个答案:

答案 0 :(得分:0)

class ProductListView(ListView):
    context_object_name = 'products'
    model = models.Product
    template_name = "catalogue/catalogue.html"
    queryset = Product.objects.all()

    def get_category(self): 
        category_name = self.request.GET.get('category', '')
        category = None
        if category_name: 
            try:
                category = Category.objects.get(name=category_name)
            except Category.DoesNotExist, Category.MultipleObjectsReturned:
                pass
        return category

    def get_queryset(self):
        queryset = self.queryset
        category = self.get_category()
        if category:
            return queryset.filter(category=category).all()
        else:
            return queryset

    def get_context_data(self, **kwargs):
        kwargs['info_you_want'] = 'info_you_want'
        kwargs['category_list'] = Category.objects.all()
        return super(ProductListView, self).get_context_data(**kwargs)

HTML

            {% for category in category_list%}
                <a href="{% url 'product_list' %}?category={{ category.id }}">
                    {{ category.name }}
                </a>
            {% endfor %}

您要设置的属性为queryset而不是products,对于带有类别主电源的产​​品,请询问网址'www.example.com/products/?category=mains',对于带有类别杂物的产品,请询问网址'www.example.com/products/?category=sundries'

答案 1 :(得分:0)

简短的方式

{{1}}

请记住,您正在使用通用模板 当然这是指南,您需要在此版本的代码中进行细节更改。 (编辑)的