I am following Mosh course (Python for beginner (6 hrs)). In the Django project, When listing the products from the database with HTML/Python/Django code. The output not showing it correctly. In fact, it shows blank after the h1 tag.
View module code.
JavaScript
x
13
13
1
from django.shortcuts import render
2
from products.models import Product
3
4
5
def index(request):
6
products = Product.objects.all()
7
return render(request, 'index.html',
8
{'product': products})
9
10
11
def new_products(request):
12
return HttpResponse('The Following are our new Products')
13
HTML Code.
JavaScript
1
6
1
<ul>
2
{% for product in products %}
3
<li>{{ product.name }}</li>
4
{% endfor %}
5
</ul>
6
The output just show heading Products
Advertisement
Answer
you have a typo. In the context data you provide to your template you are using the key ‘product’ for your queryset:
JavaScript
1
3
1
return render(request, 'index.html',
2
{'product': products})
3
In the template you are referencing ‘products’ which is not defined.
JavaScript
1
2
1
{% for product in products %}
2
Update the name for your queryset to products: {‘products’: products}
Recommend installing the django debug toolbar. You can view the context passed to the template.