我无法在主页中添加我的category title
网址。有我的代码和错误。我可以添加而不是{{ c.get_absolute_url }}
。我在这里缺少什么?
models.py
class Category(models.Model):
title = models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
is_active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
class Meta(object):
verbose_name_plural = 'Categories'
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("category_url", kwargs={"slug": self.slug })
class Product(models.Model):
name = models.CharField(max_length=120, unique=True)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=20)
is_active = models.BooleanField(default=True)
slug = models.SlugField(max_length=200, unique=True)
categories = models.ManyToManyField('Category', blank=True)
stock = models.IntegerField()
timestamp = models.DateTimeField(auto_now_add=True)
images = models.ImageField(upload_to='images', blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("product_detail", kwargs={"slug": self.slug})
views.py
class HomePageView(ListView):
model = Product
context_object_name = 'product_list'
template_name = 'products/index.html'
def get_queryset(self):
return Product.objects.all()
urls.py
url(r'^$', HomePageView.as_view(),
name='home'),
url(r'^category/(?P<slug>[-\w]+)/$',
CategoryProductList.as_view(),
name='category_detail'),
url(r'^(?P<slug>[-\w]+)/$',
ProductPageView.as_view(),
name='product_detail'),
的index.html
{% for product in product_list %}
<a href="{{ product.get_absolute_url }}">{{ product.name }}</a>
{% for c in product.categories.all %}
<a href="{{ c.get_absolute_url }}">{{ c.title }}</a>
{% endfor %}
{{ product.description }}
{% endfor %}
ERROR
NoReverseMatch at /
Reverse for 'category_url' with arguments '()' and keyword arguments '{'slug': 'vans'}' not found. 0 pattern(s) tried: []
答案 0 :(得分:1)
在您的模型中,您拨打category_url
,但在您的网址中category_detail
,请替换get_absolute_url
功能:
def get_absolute_url(self):
return reverse("category_detail", kwargs={"slug": self.slug})