【发布时间】:2020-10-14 14:29:27
【问题描述】:
我想遍历一个在元组模板中传递的列表。我想在它们的相对位置显示一些描述。我有一个列表中的所有描述(7-8)。 这是views.py文件的样子:
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)
模板 mainapp/index.html 看起来像:
{% 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 %}
我想在每张卡片的 {{post.3}} 位置显示相关描述,但它是一个完整列表。
【问题讨论】: