![](/img/trans.png)
[英]django calling a python script shows the html code instead of a webpage
[英]Browser Output of HTML/Django/Python shows nothing of Python code
我正在学习 Mosh 课程(Python 初学者(6 小时))。 在 Django 项目中,当使用 HTML/Python/Django 代码列出数据库中的产品时。 output 没有正确显示。 事实上,它在 h1 标签后显示空白。
查看模块代码。
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 代码。
<ul>
{% for product in products %}
<li>{{ product.name }}</li>
{% endfor %}
</ul>
output 只显示标题 产品
你打错了。 在您提供给模板的上下文数据中,您正在为查询集使用键“产品”:
return render(request, 'index.html',
{'product': products})
在模板中,您引用的是未定义的“产品”。
{% for product in products %}
将查询集的名称更新为产品:{'products': products}
推荐安装 django 调试工具栏。 您可以查看传递给模板的上下文。
Mosh 有一个非常活跃的社区,可以帮助解决这个问题,但您只获得产品标题的原因是因为这就是您在 for 循环 {{ product.name }} 中要求的全部内容。 我还没有完成课程,但是 model 将具有您可以调用的其他属性,即 {{ product.image }} 等删除名称应该打印所有内容 {{ product}}
在模型定义中,检查产品的列。它可能是这样的
class Product(models.Model):
name=models.TextField()
price=models.IntegerField()
details=models.TextField()
在您的 HTML 定义中,添加一行
<ul>
{% for product in products %}
<li>{{ product.name }}</li>
<li>{{product.price}}</li>
{% endfor %}
如果您想从数据库中添加任何额外信息,请执行此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.