我想将category_slug或id_slug用于detailview作为productdetailview
并在那里显示该类别的所有产品,但我不知道该怎么做
我使用了这些视图,但收到404错误。为什么productdetailview
和categorydetailview
之间有区别?请问可以帮助我解决这个问题吗?
models.py
class Category(models.Model):
name = models.CharField(max_length=120,unique=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Brand(models.Model):
name = models.CharField(max_length=120,unique=True)
class Product(models.Model):
category = models.ManyToManyField(Category,blank=True)
brand = models.ForeignKey(Brand,on_delete=models.CASCADE)
car = models.ForeignKey(Car,on_delete=models.CASCADE)
title = models.CharField(max_length=120,unique=True)
slug = models.SlugField(unique=True)
description = models.TextField(max_length=10000)
price = models.DecimalField(max_digits=10,decimal_places=2)
stock = models.PositiveIntegerField()
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
updated = models.DateTimeField(auto_now=True,auto_now_add=False)
defalut = models.ForeignKey(Category,related_name="defalut_category",blank=True,null=True,on_delete=models.CASCADE)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('products:product_detail',kwargs={"slug":self.slug})
views.py
def ProductDetail(request,slug):
product = get_object_or_404(Product,slug=slug,active=True)
context = {
"product":product
}
template_name = "product_detail.html"
return render (request,template_name,context)
def CategoryDetail(request,category_slug):
category = get_object_or_404(Category,slug = category_slug)
product = Product.objects.filter(category=category)
context = {
'category':category,
'product': product
}
template_name ="category_detail.html"
return render(request,template_name,context)
urls.py
app_name ='category'
urlpatterns = [
path('category-list/',views.CategoryList,name="category_list" ),
re_path(r'^(?P<category_slug>[-\w]+)/$', views.CategoryDetail, name='category_detail'),
我的错误
找不到页面(404) 请求方法:GET 要求网址:http://127.0.0.1:8000/category/elctroinc/ 提出者:products.views.CategoryDetail 没有类别与给定查询匹配。 您看到此错误是因为Django设置文件中的DEBUG = True。将其更改为False,Django将显示标准的404页面。
答案 0 :(得分:0)
问题在category_slug中,因为两个朋友说@Manjo Jadhav,@ JPG 我用id代替category_slug,它正在工作。 tnx寻求帮助的朋友。