6. Dynamically exhibiting text data

The administrative interface now allows for the addition of new products to our database. However, we need to implement specific changes to ensure these new products are dynamically displayed on the website in real time.

First we need to import all the database inside our views.py file, as it is the one responsible for what is displayed on each url:

from .models import *

Then, in the views.py file, we will create a variable named context within the functions of the urls. This variable will serve as a container for a dictionary of key-value pairs that represent the data to be rendered on the corresponding URL. By populating context with information from the database, we can ensure that the views.py file dynamically generates and displays content on the associated web pages.

def store(request):
    products = Product.objects.all() #? grabbing all products from the database (queryset)
    context = {"products" : products} 
    return render(request, 'store.html', context) 

In order to display each value of the list products, Django allows us to use some python features inside html files such as conditions and for loops as seen below:

Inside the block body
{% for product in products %}
{% endfor %}

{% if 'condition' %}
{% else %}
{% endif %}

Using this format, we will display the name and price of each product on our database inside the store page by iterating through the product list:

Block body of store.html
<% for product in products %>

<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>

<% endfor %>
Product details can differ depending on the specific information stored in each database.

Last updated