|
1 | | -from django.shortcuts import render |
| 1 | +from django.shortcuts import render, get_object_or_404 |
| 2 | +from django.views import generic |
2 | 3 |
|
3 | 4 | from .models import Product, Category |
4 | 5 |
|
5 | | -def product_list(request): |
6 | | - context = { |
7 | | - 'product_list': Product.objects.all() |
8 | | - } |
9 | | - return render(request, 'catalog/product_list.html',context) |
| 6 | +class ProductListView(generic.ListView): |
10 | 7 |
|
11 | | -def category(request, slug): |
12 | | - category = Category.objects.get(slug = slug) |
13 | | - context = { |
14 | | - 'current_category': category, |
15 | | - 'product_list': Product.objects.filter(category = category), |
16 | | - } |
17 | | - return render(request, 'catalog/category.html',context) |
| 8 | + model = Product |
| 9 | + template_name = 'catalog/product_list.html' |
| 10 | + |
| 11 | +product_list = ProductListView.as_view() |
| 12 | + |
| 13 | + |
| 14 | +class CategoryListView(generic.ListView): |
| 15 | + |
| 16 | + template_name = 'catalog/category.html' |
| 17 | + context_object_name = 'product_list' |
| 18 | + |
| 19 | + def get_queryset(self): |
| 20 | + return Product.objects.filter(category__slug = self.kwargs['slug']) |
| 21 | + |
| 22 | + def get_context_data(self, **kwargs): |
| 23 | + context = super(CategoryListView, self).get_context_data(**kwargs) |
| 24 | + context['current_category'] = get_object_or_404(Category, slug = self.kwargs['slug']) |
| 25 | + return context |
| 26 | + |
| 27 | +category = CategoryListView.as_view() |
| 28 | + |
| 29 | +#-------------------------------------------------Maneira tradicional |
| 30 | +# def category(request, slug): |
| 31 | +# category = Category.objects.get(slug = slug) |
| 32 | +# context = { |
| 33 | +# 'current_category': category, |
| 34 | +# 'product_list': Product.objects.filter(category = category), |
| 35 | +# } |
| 36 | +# return render(request, 'catalog/category.html',context) |
18 | 37 |
|
19 | 38 |
|
20 | 39 | def product(request, slug): |
|
0 commit comments