Passing an integer through the url to make a product page

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

In order to complete this tutorial you will need to have followed the previous tutorials to create the Product and Review models. In this tutorial we will make it so the product is passed through the url, and then used to display just that product. So we could use'/product/1' to display the produce with the id number of 1.

We need to define a new path in the 'urlpatterns', add the following:

path('product/<int:prodID>/', myapp.views.showproduct, name='showproduct'),

This will create a url for '/product/' and the value you enter, ie '/product/1' will be used as an integer and will be called 'prodID'.

The path in the '' above points to a 'showproduct' method, we will need to create this in the ''. To pass the url parameter we will need to include it in the arguments:

def showproduct(request, prodID):
    product_info = {
        'products' : Product.objects.filter(pk = prodID),
        'reviews' : Review.objects.filter(product = prodID)
    return render(request, 'MyApp/showproduct.html', product_info)

'prodID' is passed into the procedure by the arguments, and then used to filter the product model by the primary key and then filter the review model by the product field.


You need to create a new html file in the templates folder, this should already have one for 'products.html'. Open this and save it has 'showproduct.html', then edit it to get the following:

{% extends "MyApp/base.html" %}

{% block title %} Product {% endblock %}

{% block content %}

    {% for product in products %}

	<h1> {{ }} - {{ product.manufacturer }} </h1>
	<p> {{ product.description | safe | linebreaks}} </p>
	<p> Date Added: {{ product.date_added }} </p>

        <h2> Reviews </h2>

        {% for review in reviews %}

            <p> {{ review.date_posted }} - {{ }} <br>

            {{ review.review_text }} <br>

            {{ review.product_rating }} out of 10 </p>

        {% endfor %}

    {% endfor %}

{% endblock %}

The main changes are the additional for loop for the reviews.