10. View product page

Having implemented the category filter, our next objective is to enhance the product visualization experience. This will involve developing a dedicated page to display detailed information about the selected product. Additionally, we will incorporate a feature allowing users to alternate between the product's available colors.

Inside the store urls.py file we will create a new path for the product page as follow:

store\urls.py
path('product/<int:product_id>', view_product, name="view_product"),

The URL for each individual product page will be dynamically generated to include the unique identifier associated with each product.

Important note: the product_id variable will receive a integer id value that is generated automatically by Django after creating the classes.

In the views.py file, we'll define a new function to handle the view for individual product pages. This function will accept a product_id parameter in its URL, which will correspond to the unique identifier for the desired product.

views.py
def view_product(request, product_id) :
    product = Product.objects.get(id=product_id) #? id parameter is created automatically by django
    context = {'product': product}
    return render(request, 'view_product.html', context)

Now, inside the templates folder, we will create a new html file 'view_product.html'

view_product.html
{% extends 'base.html' %}
{% load static %}

{% block body %}

<h3>
    {{ product.name }}
</h3> 

<img src="{{ product.image.url }}" width = "300" height = "450"> <!--returns the url of the image -->
<p>Product: {{ product.name }}</p>  <!-- Originally, what will be displayed in product is what is returned in its respective __str__ function on the models file-->
<p>Price: {{ product.price }}</p>

<button>Add to Cart</button>

{% endblock %}

To enable navigation to individual product visualization pages, we'll embed hyperlinks in the store.html template. Clicking on a product displayed on the store page will direct users to the corresponding product detail view. The hyperlinks will include the appropriate URL pattern, passing the unique product_id as a parameter to dynamically generate the correct endpoint for each product's detailed view.

store.html
{% for product in products %}

<a href = {% url 'view_product' product.id %}>
    <img src="{{ product.image.url }}" width = "300" height = "450"> <!--returns the url of the image -->
</a>

By clicking on a product within the store page, we are now directed to a dedicated page that contains detailed information about that product.

Page containing the details of only one product

Last updated