简体   繁体   English

HTML/Django/Python 的浏览器 Output 没有显示 Python 代码

[英]Browser Output of HTML/Django/Python shows nothing of Python code

I am following Mosh course (Python for beginner (6 hrs)).我正在学习 Mosh 课程(Python 初学者(6 小时))。 In the Django project, When listing the products from the database with HTML/Python/Django code.在 Django 项目中,当使用 HTML/Python/Django 代码列出数据库中的产品时。 The output not showing it correctly. output 没有正确显示。 In fact, it shows blank after the h1 tag.事实上,它在 h1 标签后显示空白。

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. HTML 代码。

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

The output just show heading Products output 只显示标题 产品

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}将查询集的名称更新为产品:{'products': products}

Recommend installing the django debug toolbar.推荐安装 django 调试工具栏。 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 }}. Mosh 有一个非常活跃的社区,可以帮助解决这个问题,但您只获得产品标题的原因是因为这就是您在 for 循环 {{ 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}}我还没有完成课程,但是 model 将具有您可以调用的其他属性,即 {{ product.image }} 等删除名称应该打印所有内容 {{ 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在您的 HTML 定义中,添加一行

<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如果您想从数据库中添加任何额外信息,请执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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