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.
from django.shortcuts import render
from products.models import Product
def index(request):
products = Product.objects.all()
return render(request, 'index.html',
{'product': products})
def new_products(request):
return HttpResponse('The Following are our new Products')
HTML Code.
<ul>
{% for product in products %}
<li>{{ product.name }}</li>
{% endfor %}
</ul>
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:
return render(request, 'index.html',
{'product': products})
In the template you are referencing ‘products’ which is not defined.
{% for product in products %}
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.