Difference between revisions of "Display data from a model in django"
(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...") |
(→products template) |
||
Line 24: | Line 24: | ||
=products template= | =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'. | + | 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: |
− | |||
<syntaxhighlight lang=html> | <syntaxhighlight lang=html> | ||
{% extends "MyApp/base.html" %} | {% extends "MyApp/base.html" %} | ||
Line 45: | Line 44: | ||
{% endblock %} | {% endblock %} | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | 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'. |
Revision as of 22:01, 16 September 2019
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 %}
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'.