Display data from a model in django

From TRCCompSci - AQA Computer Science
Revision as of 22:59, 16 September 2019 by Admin (talk | contribs) (Created page with "=views.py= 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: <syntaxhighl...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

views.py

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.

urls.py

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