如何在Django中显示python脚本中的数据?

时间:2019-10-08 18:07:00

标签: python django

我创建了一个程序,该程序可以抓取数据并将其存储为JSON格式。

通常,当我想在Python中显示数据时,我会使用以下代码:

product_list = daily_deals()

for i in range(len(product_list)):
        print("Name: ", product_list[i]["name"])
        print("Price: ", product_list[i]["price"])
        print("Old Price: ", product_list[i]["old_price"])
        print("Link: ", product_list[i]["link"])
        print("Image: ", product_list[i]["img"])
        print()

当我想在Django中做同样的事情时,我将脚本添加到了索引视图中(因为数据将显示在主页中)

views.py

def index(request):
    template = loader.get_template("search/index.html")

    daily_deals_list = daily_deals.deal_scraper
    return HttpResponse(template.render({}, request), daily_deals_list)

然后在我的index.html中:

{% for product in daily_deals_list %}
    <div class="deal-item">
       <a class="deal-product-link" href="{{ product.link }}" target="_blank">
       <div class="deal-img-block">
           <img class="deal-img" src="{{ product.img }}">
       </div>
       <p class="deal-product-name text-center">{{ product.name }}</p>
       <p class="deal-product-price text-center" style="color: orange;"> 
       <span class="deal-old-price" style="text-decoration:line-through;">{{ product.old_price }}</span>&emsp; {{ product.price }}</p>
       </a>
       </div>
{% endfor %}

2 个答案:

答案 0 :(得分:2)

您可能需要致电Deal_scraper,因此不用daily_deals.deal_scraper来进行daily_deals.deal_scraper()

答案 1 :(得分:1)

呈现模板时,您要设置一个空的上下文,该上下文基本上是一个包含要发送到模板的所有内容的字典,因此,如果要创建一个名为daily_deals_list的列表,代码可以简单得多:

def index(request):
    template = loader.get_template("search/index.html")
    return HttpResponse(template.render({
        "daily_deals_list": daily_deals()
    }, request))

(在您的第一个示例中,daily_deals()返回了产品列表)