Beginner having trouble mapping views to urls

Brand new to Django, and running through the beginner tutorial, I made some adjustments to model an e-commerce site I hope to develop using Django. I’ve successfully set up an index view/url/template to display a list of all available products as links to the individual products, but clicking the link returns a debug 404 page.

The bad link is generated in my index template as (some HTML committed):
{% if products_list %}
unordered list
{% for product in products_list %}
a href="/detail/{{ }}/">{{ }}
{% endfor %}
/unordered list
{% else %}
No products are available.
{% endif %}

And now my detail code, I am attempting to think this view to display unique info depending upon which product link is clicked:

def detail(request, product_id):
product = Product.objects.get(pk=product_id)
except Product.DoesNotExist:
raise Http404(“Product does not exist”)
return render(request, ‘webCart/detail.html’, {‘product’: product})

path(‘detail/int:product_id/’, views.detail, name=‘detail’)

DETAIL TEMPLATE (some HTML committed):

h1-product name
unordered list
{% for description in product.description_set.all %}
{{ product.description }}
{% endfor %}
/unordered list

Right now clicking a product on the index page returns the URL: where four is the product id I clicked on

Again I am very new to Django and thank anyone/everyone who takes the time to help with what is no doubt a very clumsy beginner’s mistake.

Unfortunately, due to how this forum works, there are a number of changes that it made to your code that make it look like there are some problems that probably aren’t there - but can’t be sure.

When you’re posting code, please make sure you mark it as “preformatted text” that way, statements like:

<this is a test>

don’t end up looking like:

(In which case, the forum has completely hidden my text.)


Hi, this is not how you construct urls in templates

a href="/detail/{{ }}/">{{ }}

You should construct the url using url tag (see

<a href="{% url 'detail' %}">{{ }}</a>

This approach protects you from mistakes like you did in your code where you register the url as ‘detail/int:product_id/’ but then try to access it as “product/4/” (it’s detail vs product confusion).

Thank you both for your replies,

Constructing the url in template as described above solved my problem, this is very much appreciated!

1 Like