Designing simple product HTML templates

Now that we have exposed our product data via generic views and created corresponding URL patterns, we need to implement some templates to render the product information to our browser. Another advantage of using generic views is that templates are automatically specified for each view based upon the name of the application and model in use. Since our urls.py file is part of the products application and we are rendering generic views on our Product model, our application will automatically look for templates in the following locations within the template folder: products/product_detail.html and products/product_list.html.

These templates will get rather simple contexts. The object_list template will receive a variable whose default name is object_list. It is a QuerySet corresponding to the data exposed by your view. The object_detail template will receive a variable whose default name is object. It corresponds to the object you are viewing in more detail.

In our example, the list view will receive a QuerySet of all Product objects, while the detail view receives the object specified by the slug in the URL. In our list template we loop over the products like so (extra HTML portions are removed):

{% for object in object_list %}
 <h3><a href="{{ object.get_absolute_url }}">
 {{ object.name }}</a></h3>
 <p>{{ object.description }}</p>
{% endfor %}
Designing simple product HTML templates

The detail template works similarly, though the output in the template includes more details about the item:

<h1>{{ object.name }}</h1>
<p>{{ object.description }}</p>
<p>Price: ${{ object.price_in_dollars }}</p>
<hr/>
<p><a href="{% url product_list %}">Back to product list</a></p>
Designing simple product HTML templates

We can print the extra attributes, if any happen to exist, very easily in the template. The output from the snippet below is demonstrated in the following screenshot:

<h1>{{ object.name }}</h1>
<p>{{ object.description }}</p>
<p>Price: ${{ object.price_in_dollars }}</p>
{% for detail in object.details.all %}
{% if forloop.first %}<p>Additional details:</p>{%endif%}
<li>{{ detail.attribute.name }}: {{ detail.value }}</li>
{% endfor %}
Designing simple product HTML templates

We now have a very spartan, but functional product catalog rendering to HTML from our Django database. We can add, modify, and delete products, catalogs and additional attributes. Now let's get started selling. In the next section we will create a Google Checkout API account and use its sandbox to set up a simple order mechanism for our online store.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset