0

I want to iterate over a list which is passed in template in a tuple. I want to show some descriptions in their relative places. I have all the descriptions(7-8) in a list. Here is views.py file looks like:

from django.shortcuts import render

import requests
from bs4 import BeautifulSoup
from .functions import get_descriptions


def index(request):

    url = requests.get('https://thehackernews.com/')
    soup = BeautifulSoup(url.content, 'html.parser')

    post_container = soup.find(class_='blog-posts')
    post_body = post_container.find_all(class_='body-post')
    total_news = range(0, len(post_body))

    descs = get_descriptions(post_body=post_body) # a list of descriptions

    final_postings = []
    for link in post_body:
        post_link = link.find(class_='story-link').attrs
        lnk_lst = str(post_link['href'])
        # print(lst)

        images = link.find(class_='home-img-src').attrs
        src_lst = str(images['data-src'])
        # print(src_lst)

        titles = link.find(class_='home-title').get_text()

        post_dates = link.find(class_='item-label').get_text()

        final_postings.append((lnk_lst, src_lst, titles, descs))

    front_end_stuff = {'final_postings': final_postings, 'news': total_news}
    return render(request, 'mainapp/index.html', context=front_end_stuff)

And the template mainapp/index.html looks like:

{% extends 'mainapp/main.html' %}

{% block content %}

{% for post in final_postings %}
<div class="card hoverable">
    <div class="card-content">
        <div class="row">
            <div class="col s12 l4">
                <div class="card-image">
                    <img src="{{ post.1 }}" alt="news" class="responsive-img">
                </div>
            </div>
            <div class="col s12 l7 offset-l1">
                <a href="{{ post.0 }}" class="black-text"><div class="title">{{ post.2 }}</div></a>
                <p class="truncate">{{ post.3 }}</p>
            </div>
        </div>
    </div>
</div>
{% endfor %}

{% endblock content %}

I want to show the relative description to be shown in each card at position of {{post.3}} but it is a full list.

2 Answers2

0

Given you've stated that {{post.3}} renders a full list, you can access individual items by iterating over the list.

{% for item in post.3 %}
    <p class="truncate">{{ item }}</p>
{% endfor %}

Replace the line <p class="truncate">{{ post.3 }}</p> with the lines above.

You can read this Section of the Official Django Documentation to understand how template tags work. A Similar Question could also help you understand how it works.

Wangwe
  • 171
  • 1
  • 6
0

I create my own template tag and use it in the template and for iterating over one item on one post I used Django's default for loop variables