【问题标题】:Django displaying model on web pageDjango在网页上显示模型
【发布时间】:2017-11-21 20:01:27
【问题描述】:

我不确定我哪里出错了。我正在使用 Django/HTML/Foundations 创建一个网上商店,但我无法让数据库中的产品显示在网页上。我知道它们在数据库中,因为当我进入管理页面时,它们就会出现。

这是 HTML 片段:

{% for products in Product %}
<div class="column">
  <h5>Title: {{products.product_name}}</h5>
  <h5>Type: {{products.product_type}}</h5>
  <h5>Price: {{products.sales_price}}</h5>
  <img class="thumbnail" src="http://placehold.it/550x550">
</div>
{% endfor %}

这是模型:

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    product_type = models.CharField(max_length=100)
    sales_price = models.CharField(max_length=10)g

    def __str__(self):
        return self.product_name + " " + self.product_type + " " + self.sales_price 

我的views.py产品页面中唯一的内容是:(可能是我的问题所在)

def products(request):
    return render(request,"products.html")

我是 django 和 python 的新手。有人可以解释发生了什么吗?谢谢

【问题讨论】:

    标签: python html django model-view-controller


    【解决方案1】:

    您的视图需要使用context 参数向模板提供products 信息。 See the documentation for render().

    views.py:

    def products(request):
        context = {'products':Product.objects.all()}
        return render(request,"products.html",context)
    

    products.html:

    {% for product in products %}
    <div class="column">
         <h5>Title: {{product.product_name}}</h5>
         <h5>Type: {{product.product_type}}</h5>
         <h5>Price: {{product.sales_price}}</h5>
         <img class="thumbnail" src="http://placehold.it/550x550">
    </div>
    {% endfor %}
    

    【讨论】:

    • 您可能会使用 ListView,即 generic view 和您的模板来归档相同的内容
    【解决方案2】:

    您是否尝试过更改您的 for 循环

    {% for products in Product %}
    

    {% for product in products %}
    

    因为您希望在每次处理循环时显示一组产品中的单个产品。

    【讨论】:

    • 是的,我尝试将其更改为那个,没有更改。我对python有点陌生,但我写它的方式是为了(模型名称)中的(一些组成的变量)。然后访问模型中的变量,它是 products.variableName。我做对了吗?在这里的调整中,它被翻转(首先是模型,然后是一些创建的变量)。但它的工作方式没有区别。
    猜你喜欢
    • 2019-09-03
    • 2018-11-13
    • 2021-02-03
    • 2019-02-26
    • 1970-01-01
    • 2015-04-23
    • 2017-09-14
    • 2021-08-01
    • 2016-10-15
    相关资源
    最近更新 更多