简体   繁体   中英

Browser Output of HTML/Django/Python shows nothing of Python code

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

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.

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 ie {{ product.image }} etc removing name should print everything {{ product}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM