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/{{ product.id }}/">{{ product.name }}
{% 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:

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

URL PATH:
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:
127.0.0.1:8000/product/4/ 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.)

Ken

Hi, this is not how you construct urls in templates

a href="/detail/{{ product.id }}/">{{ product.name }}

You should construct the url using url tag (see https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#url)

<a href="{% url 'detail' product.id %}">{{ product.name }}</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