Display data from a model in django

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


Within your app folder, load the 'views.py' file. You will need to add the following import statement to import the product model you created earlier:

from .models import Product

Now create a new method called products:

def products(request):
    product_info= {
        'products': Product.objects.all()
    return render(request, 'MyApp/products.html', product_info)

The 'product_info' will contain the data for each product currently entered. This will be passed into the 'products.html' template.


Within your project folder, load the 'urls.py' file. You need to add the following into the 'urlpatterns':

path('products/', myapp_views.products, name='products'),

products template

You need to create a new html file in the templates folder, this should already have 'base.html' and 'home.html'. The new file should be saved as 'products.html'. Enter the following:

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

{% block title %}Products{% endblock %}

{% block content %}

       {% for product in products %}

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

The code above is a for loop to cycle through each product in the product model, then for each product it writes the 'name' followed by a '-' and then the manufacturer. It writes out the 'description' and then the 'date_added'.

base template

You will also need to create a link in the 'base.html' for the new 'products' page. So find the following html for the navigation bar:

    <ul class="nav navbar-nav">
      <li><a href="/">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>

Edit the 'Page 1' link so that it links to our 'products' page:

    <ul class="nav navbar-nav">
      <li><a href="/">Home</a></li>
      <li><a href="{% url 'products' %}">Products</a></li>
      <li><a href="#">Page 2</a></li>


You should have already entered some products when you tested your model, if you haven't run the server and add '/admin' to the address.

Enter the address for the products page, this should be ''.