0

I recently coded a script that scrapes headlines and images off of https://thestar.com ( The Toronto Star ), It takes the first 10 h3 elements from the site and the corresponding images ( 10 img elements ), and displays them on my news aggregator website.

However , my index.html file is having a problem.

enter image description here

As you can see, instead of displaying the images in order by its corresponding headline, its just displaying ALL of the images in every single headline.

All i need is for each image from the 10 images seen in the screenshot i put up above to show one by one in order next to each headline.

Here's the code for the container element that is displaying the headlines and images in my html file :

<div class="col-6">
        <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center>
        {% for n in toi_news %}
        <strong><h5>{{n}}</h5></strong>
        {% for i in images %}
        <img src="{{i}}">
        {% endfor %}
        <hr>
        {% endfor %}
        <br>
    </div>

Can anyone help me? Any help would be greatly appreciated.

1 Answer 1

1

You need to loop through the images and the headlines concurrently not nesting the image loop in the headline loop.

<div class="col-6">
    <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center>
    {% for i, n in zip(images, toi_news) %}
    <strong><h5>{{n}}</h5></strong>
    <img src="{{i}}">
    <hr>
    {% endfor %}
    <br>
</div>

If you cant you the above syntax you can loop over an index for both lists

<div class="col-6">
    <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center>
    {% for x in range(len(toi_news)) %}
    <strong><h5>{{toi_news[x]}}</h5></strong>
    <img src="{{images[x]}}">
    <hr>
    {% endfor %}
    <br>
</div>
Sign up to request clarification or add additional context in comments.

4 Comments

Its giving me this error: TemplateSyntaxError at / 'for' statements should use the format 'for x in y': for i, n in zip(images, toi_news)
Well maybe try iterating via an index
its now giving me this error lol : TemplateSyntaxError at / Could not parse the remainder: '(len(toi_news))' from 'range(len(toi_news))'
Apparently you cant perform method calls in django templates. is there any other alternative you can help me out with?

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.