I can't display url tag in template

Question:

views.py

def Product_details (request , product_name):
    product_detail = Product.objects.get(pk=product_name)
    return render (request, 'product_detail.html', {
      'product_detail' : product_detail,
})

urls.py

urlpatterns = [

  path('', views.Product_list , name= 'Product_list'),
  path('product/<int:product_name>/', views.Product_details , name= 'Product_details'),

product_detail.html

<a href="{% url 'Product_details' product.name %}

I can’t display the URL tag on the page.

Asked By: Mr Amir

||

Answers:

In your urls.py file, add this variable above urlpatterns:

app_name = "products"

and then try accessing it like this:

<a href="{% url 'products:Product_details' product.name %}">click me</a>

Answered By: Hammad

First app_name should only appear once in a given urls.py file. You are also importing modules that don’t seem to be needed in your urls.py file. Right now you seem to have:

from django.urls import path 
from .import views 
from django.conf import settings 
from .forms import OrderForm 
from django.conf.urls.static import static 

app_name = 'Product_list' 
app_name = 'OrderForm' 
app_name = 'SpecialProduct' 
app_name = 'products'

urlpatterns = [ 
    path('', views.Product_list , name= 'Product_list'),
    path('product/<int:product_name>/', views.Product_details , name= 'Product_details'), 
    path('qa/', views.Question_list , name= 'Question_list'), 
    path ('order/' , views.OrderForm , name='OrderForm'),
]

So, change the above file to:

from django.urls import path 
from .import views 
 
app_name = 'products'

urlpatterns = [ 
    path('', views.Product_list , name= 'Product_list'),
    path('product/<int:product_name>/', views.Product_details , name= 'Product_details'), 
    path('qa/', views.Question_list , name= 'Question_list'), 
    path ('order/' , views.OrderForm , name='OrderForm'),
]

Next, do what @Hammad suggests:

<a href="{% url 'products:Product_details' product.name %}">click me</a>

Next
You have pk=product_name and path('product/<int:product_name>/' which suggest that the product_name is the primary key, and an integer. The term name generally refers to a string, not an integer, which iw why I wanted to see your Product class.

Answered By: raphael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.