i’m learning django and I spent a long time to let reverse() work but I failed.
I don’t want to use {% url ”….%}.
this is the models.py
I created 2 tables Category & Product
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.name
this is urls.py
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('product' , views.all_products , name= 'products'),
path('product/<int:product_id>/', views.product_detail, name='product_detail'),
]
this is views.py
from django.shortcuts import render, get_object_or_404
from django.urls import reverse , reverse_lazy
from .models import Product
def all_products(request):
products = Product.objects.all()
context = {
'products' : products
}
return render(request , 'index.html',context)
def product_detail(request, product_id):
product = get_object_or_404(Product, id=product_id)
detail_url = reverse_lazy ('myapp:product_detail', args = [product_id])
return render(request, 'product_detail.html', {
'product': product,
'detail_url': detail_url,
})
this is index.html
The problem is reverse function when I click on achor tag i didn’t opens the detail_page
<!DOCTYPE html>
<html>
<head>
<title>Product Detail</title>
</head>
<body>
{% for product in products%}
<a href="{% url 'myapp:product_detail' product.id%}" onclick="show()"><h1>{{ product.name }}</h1></a>
{% endfor%}
<!-- -->
</body>
</html>
this is product_detail.html
{{product}}
type here