Home > database >  Django url link error Reverse for 'category' with keyword arguments '{'category.
Django url link error Reverse for 'category' with keyword arguments '{'category.

Time:08-28

I'm trying to create a product filter, filtering it by category, so I decided to send the category id trough an URL and then filter all products by the specified ID, but im getting troubles to implement it.

Reverse for 'category' with keyword arguments '{'category.id': 1}' not found. 1 pattern(s) tried: ['category/<int:category\\.id\\Z']

views.py:

def category(request, category_id):
    products = Product.objects.filter(category=category_id)
    return

 render(request, 'product/category.html', {'products': products})

models.py:

class Category(models.Model):
    name = models.CharField(max_length=255, unique=False, blank=True)
    slug = models.SlugField(unique=True)

    def __str__(self):
        return self.slug

    def get_absolute_url(self):
        return reverse("product:category", kwargs={"category.id": self.id})

urls.py:

urlpatterns = [
    path('', views.index, name="index"),
    path('detail/<int:product_id', views.detail, name="detail"),

    path('category/<int:category.id', views.category, name="category")
]

HTML Template, I tried two ways,none of them worked:

{% for category in categories %}
{{category.id}}
<a href="{{category.get_absolute_url}}"></a>
{% comment %}
<a href="{% url 'product:category' category_id=category.id %}"></a>
{% endcomment %}
{% endfor %}

models.py:

class Product(models.Model):
    name = models.CharField(max_length=255, unique=False, blank=True)
    slug = models.SlugField(unique=True)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, unique=False)

CodePudding user response:

It should be category_id not category.id in urls.

Also need > at the end with closing /, so try below urls:

urlpatterns = [
    path('', views.index, name="index"),
    path('detail/<int:product_id>/', views.detail, name="detail"),

    path('category/<int:category_id>/', views.category, name="category")
]
  • Related