Делаю вывод товара по категориям.
Есть
Типы продуктов. Из них выводятся
Главные категории. Из главных категорий должны выводиться
категории товаров.
Ну например:
Инструменты >> Струнные >> Электрогитары >> Конечный список товаров. Из
инструментов выводятся
главные категории, а из
Главных категорий не выводятся
категории товара.
При переходе на любую
категорию товара выводит такую ошибку
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/strings/
Raised by: shop.views.product_list
_____________________________________________________
No ProductType matches the given query.
Вот мой
models.py:
from django.db import models
from datetime import datetime
from django.urls import reverse
class ProductType(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
type_available = models.BooleanField(default=True)
class Meta:
ordering = ('name',)
verbose_name = 'Тип продукта'
verbose_name_plural = 'Типы продуктов'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:by_product_type', args=[self.slug])
class MainCategory(models.Model):
product_type = models.ForeignKey(ProductType, on_delete=models.DO_NOTHING, related_name='types')
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 = 'Главная категория'
verbose_name_plural = 'Главные категории'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:by_main_category',
args=[self.slug])
class Category(models.Model):
product_type = models.ForeignKey(ProductType, default=666, on_delete=models.DO_NOTHING, related_name='category_product_types')
main_category = models.ForeignKey(MainCategory, default=666, on_delete=models.DO_NOTHING, related_name='categories')
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 = 'Категория'
verbose_name_plural = 'Категории'
def get_absolute_url(self):
return reverse('shop:product_list_by_category',
args=[self.slug])
def __str__(self):
return self.name
class Product(models.Model):
product_type = models.ForeignKey(ProductType, default=666, on_delete=models.DO_NOTHING, related_name='product_types')
main_category = models.ForeignKey(MainCategory, default=666, on_delete=models.DO_NOTHING, related_name='product_main_category')
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='products')
company = models.ForeignKey(Company, on_delete=models.DO_NOTHING)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
detail_image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Продукт'
verbose_name_plural = 'Продукты'
ordering = ('name',)
index_together = (('id', 'slug'),)
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
views.py:
from django.shortcuts import render, get_object_or_404
from .models import Category, Product, ProductType, MainCategory
from cart.forms import CartAddProductForm
def product_list(request, type_slug=None, main_category_slug=None, category_slug=None, ):
""" Вывод списка продуктов """
product_type = None
main_category = None
category = None
product_types = ProductType.objects.all()
main_categories = MainCategory.objects.all()
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if type_slug:
product_type = get_object_or_404(ProductType, slug=type_slug)
main_categories = main_categories.filter(product_type=product_type)
categories = categories.filter(product_type=product_type)
products = products.filter(product_type=product_type)
########################################################################################################
if main_category_slug:
main_category = get_object_or_404(MainCategory, slug=main_category_slug)
categories = categories.filter(main_category=main_category)
products = products.filter(main_category=main_category)
########################################################################################################
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
########################################################################################################
return render(request,
'shop/product/list.html',
{'product_type': product_type,
'product_types': product_types,
'main_category': main_category,
'main_categories': main_categories,
'category': category,
'categories': categories,
'products': products})
urls.py:
from django.conf.urls import url
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
url(r'^$', views.product_list, name='product_list'),
path('<slug:type_slug>/', views.product_list, name='by_product_type'),
path('<slug:main_category_slug>/', views.product_list, name='by_main_category'),
path('<slug:category_slug>/', views.product_list, name='product_list_by_category'),
url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'),
]
Так я вывожу список категорий(которые не выводятся):
<div class="row mb-4">
<div class="col-md-12">
<div class="btn-group btn-group-sm" role="group">
{% for c in categories %}
<button class="btn btn-secondary" type="button">
<a href="{{ c.get_absolute_url }}">{{ c.name }}</a>
</button>
{% endfor %}
</div>
</div>
</div>