Türker Yıldırım Türker Yıldırım - 2 months ago 8
Python Question

Django: ManyToMany URL in Template

I can't add URL my

category title
in homepage. There is my code and error. What i can add instead of
{{ c.get_absolute_url }}
. What i am missing here?

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: []

Answer

In your models you call category_url but in your urls you have category_detail, replace the get_absolute_url function for this:

def get_absolute_url(self):
    return reverse("category_detail", kwargs={"slug": self.slug})
Comments