0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Mosh has a very active community to that would help with this but the reason you are only getting product headings is because that is all you are asking for in the for loop {{ product.name }}. I have not done the course but the model will have other attributes that you can call i.e. {{ product.image }} etc removing name should print everything {{ product}}

Comments

0

In the models definition, check the columns of the product.It could be something like

class Product(models.Model):
name=models.TextField()
price=models.IntegerField()
details=models.TextField()

In your HTML definition,,add a line like

<ul>
{% for product in products %}
    <li>{{ product.name }}</li>
<li>{{product.price}}</li>

{% endfor %}

do this if you want to add any extra information from the db

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.