0

I've created a program that scrape data and store it in a JSON format.

Usually, when I want to display data in Python I use this code:

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()

When I wanted to do the same thing in Django, I added the script to the index view (because data will be displayed in the Home page)

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)

And then in my 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 %}

3
  • I'm not sure what your question is. Are you not seeing data printed in the web browser? Commented Oct 8, 2019 at 18:31
  • So what is the problem? Commented Oct 8, 2019 at 18:42
  • The problem is that the way I did it in Django is wrong. I'm not seeing anything in the browser. Commented Oct 8, 2019 at 18:54

2 Answers 2

2

You probaly need to call deal_scraper, so instead of daily_deals.deal_scraper do daily_deals.deal_scraper()

Sign up to request clarification or add additional context in comments.

Comments

1

You're setting an empty context when you render your template, the context is basically a dict with all the content you're sending to your template, so if you want to have a list called daily_deals_list, your code can be much simpler:

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

(per your first example, daily_deals() returns a product list)

1 Comment

This worked, thank you very much. However, instead of "daily_deals_list": daily_deals(), the correct way is "daily_deals_list": daily_deals_list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.