我无法在主页中添加category title
的URL。有我的代码和错误。我可以添加什么而不是{{ 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 %}
错误
NoReverseMatch at /
Reverse for 'category_url' with arguments '()' and keyword arguments '{'slug': 'vans'}' not found. 0 pattern(s) tried: []
最佳答案
在模型中,您调用category_url
,但是在您的网址中您拥有category_detail
,为此,请替换get_absolute_url
函数:
def get_absolute_url(self):
return reverse("category_detail", kwargs={"slug": self.slug})
关于python - Django:模板中的ManyToMany URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39393011/