Reputation: 695
I'm trying to route between urls. Product is a class that:
from django.db import models
from django.urls import reverse
# Create your models here.
class Product(models.Model):
title = models.TextField(max_length=20)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=20, decimal_places=2,
blank=True)
summery = models.TextField(blank=True)
feature = models.BooleanField(blank=True, null=True, default=True)
def get_absolute_url(self):
return reverse("product-detail", kwargs={"id": self.id})
and its view is like:
def product_list_view(request):
queryset = Product.objects.all() # list of objects
context = {
"object_list": queryset
}
return render(request, "products/product_list.html", context)
html:
{% block content %}
{% for instance in object_list %}
<p>{{ instance.id }} - <a href="{{ instance.get_absolute_url }}">{{
instance.title }}</a></p>
{% endfor %}
{% endblock %}
urls:
urlpatterns = [
path('', product_list_view, name='list'),
path('create/', render_initial_data, name='product_create'),
path('<int:my_id>/', dynamic_lookup_view, name='product-detail'),
path('<int:my_id>/delete/', product_delete_view,
name='product_delete'),
]
this should work but when I runserver and try to see list of products it raise this error: NoReverseMatch at /products/
while I use this method in instances of object list.
what is wrong with the #reverse
function?
Upvotes: 1
Views: 805
Reputation: 27523
def get_absolute_url(self):
return reverse("product-detail", kwargs={"id": self.id})
you have given id
as the url parameter but in url
config you have used my_id
so change anyone and use the same name
path('<int:my_id>/', dynamic_lookup_view, name='product-detail'),
Upvotes: 1