[英]Django app not displaying data in template
我是 Django 的新手,正在尝试制作我的第一个电子商务网站。 我试图从 .JSON 文件中获取产品列表以显示在我的 products.html 模板中。 产品已就位,如 Django 管理门户中所示, products
在我的views.py
文件中定义,我已经完成了loaddata
但没有任何结果。 我在下面添加了一些屏幕截图和代码以进一步解释。
Views.py 代码:
from django.shortcuts import render
from .models import Product
def all_products(request):
products = Product.objects.all()
context = {
'products': products,
}
return render(request, 'products/products.html', context)
products.html 模板:
{% extends "base.html" %}
{% load static %}
{% block page_header %}
<div class="container header-container">
<div class="row">
<div class="col"></div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="container">
<div class="row">
<div class="col">
{{ products }}
</div>
</div>
</div>
{% endblock %}
我的文件夹结构是正确的,但我会在这里发布以防万一:
任何帮助都会很棒,因为我已经坚持了一段时间了。 谢谢!
模型.py: *
class Product(models.Model):
category = models.ForeignKey('category', null=True, blank=True, on_delete=models.SET_NULL)
sku = models.CharField(max_length=254, null=True, blank=True)
name = models.CharField(max_length=254)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
image_url = models.URLField(null=True, blank=True)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
您需要遍历传递给模板的对象。 例如,
{% for product in products %}
<img src={{ product.src }} />
<h3>{{ product.title }}</h3>
<p>{{ product.desc }}</p>
{% endfor %}
到目前为止,您已经做对了大部分事情。 导致问题的一件事是模板没有迭代所有产品。
在 views.py 中,Product.objects.all() 返回一个查询集,你可以想象它是一个包含许多产品实例的列表。
因此,当 Product.objects.all() 产品被传递给模板时,您将需要使用循环来迭代产品内的实例。
我假设您的产品模型包含以下三个字段(稍后在我提供的示例中,您可以将它们替换为产品模型中的实际字段)。
现在,在 Django 模板中,您可以将 {{ products }} 替换为以下代码。
<table>
<thead>
<tr>
<th scope="col" class="text-nowrap"><span>Product</span></th>
<th scope="col" class="text-nowrap"><span>Description</span></th>
<th scope="col" class="text-nowrap"><span>Qty</span></th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td><span>{{ product.name }}</span></td><!-- Replace the name with your actual field -->
<td><span>{{ product.desciption }}</span></td><!-- Replace the desciption with your actual field -->
<td><span>{{ product.qty }}</span></td><!-- Replace the qty with your actual field -->
</tr>
{% endfor %}
</tbody>
</table>
通过上面的例子,最重要的部分是
{% for product in products %}
<tr>
<td><span>{{ product.name }}</span></td>
<td><span>{{ product.desciption }}</span></td>
<td><span>{{ product.qty }}</span></td>
</tr>
{% endfor %}
它类似于以下python代码。
for product in products:
print(product.name)
print(product.desciption)
print(product.qty)
结果,现在模板应该在桌子上显示产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.