Django: ManyToMany URL in Template
<p>I can't add URL my <code>category title</code> in homepage. There is my code and error. What i can add instead of <code>{{ c.get_absolute_url }}</code>. What i am missing here?</p>

<p>models.py    </p>

<pre><code>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})
</code></pre>

<p>views.py</p>

<pre><code>class HomePageView(ListView):
    model = Product
    context_object_name = 'product_list'
    template_name = 'products/index.html'

    def get_queryset(self):
        return Product.objects.all()
</code></pre>

<p>urls.py</p>

<pre><code>url(r'^$', HomePageView.as_view(),
    name='home'),
url(r'^category/(?P&lt;slug&gt;[-\w]+)/$',
    CategoryProductList.as_view(),
    name='category_detail'),
url(r'^(?P&lt;slug&gt;[-\w]+)/$',
    ProductPageView.as_view(),
    name='product_detail'),
</code></pre>

<p>index.html</p>

<pre><code>{% for product in product_list %}
  &lt;a href="{{ product.get_absolute_url }}"&gt;{{ product.name }}&lt;/a&gt;

  {% for c in product.categories.all %}
      &lt;a href="{{ c.get_absolute_url }}"&gt;{{ c.title }}&lt;/a&gt;
  {% endfor %}

  {{ product.description }}
{% endfor %}
</code></pre>

<p>ERROR</p>

<pre><code>NoReverseMatch at /

Reverse for 'category_url' with arguments '()' and keyword arguments '{'slug': 'vans'}' not found. 0 pattern(s) tried: []
</code></pre>

<p>In your models you call <code>category_url</code> but in your urls you have <code>category_detail</code>, replace the <code>get_absolute_url</code> function for this:</p>

<pre><code>def get_absolute_url(self):
    return reverse("category_detail", kwargs={"slug": self.slug})
</code></pre>

python django django-templates django-urls