django 模板在刷新时消失

django templates disappearing on refresh

我构建了一个新闻聚合网站,它显示 10 个标题和相应的图像,使用 bs4 从 https://thestar.com(多伦多星报)中抓取。

这里有一张照片供参考:

然而,主要问题是,每次我刷新页面时,所有元素都会消失,如下图所示:

有人知道问题出在哪里吗?

这是存储我的变量的元素:

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

这是我的 views.py 文件:

from django.shortcuts import render
import re
import json
import requests
from bs4 import BeautifulSoup
import itertools

# Getting news from The Toronto Star

toi_r = requests.get("https://www.thestar.com/?redirect=true")
toi_soup = BeautifulSoup(toi_r.content, 'html.parser')

toi_headings = toi_soup.find_all('h3')

toi_headings = toi_headings[0:10]# removing footers

toi_news = []

for th in toi_headings:
    toi_news.append(th.text)


#Getting news from the NY Times

ht_r = requests.get("https://www.nytimes.com/")
ht_soup = BeautifulSoup(ht_r.content, 'html.parser')
ht_headings = ht_soup.findAll('h3')
ht_headings = ht_headings[0:8] + ht_headings[10:12] + ht_headings[19:21]
ht_news = []

for hth in ht_headings:
    ht_news.append(hth.text)

# Getting Images from The Toronto Star

tor_r = requests.get("https://www.thestar.com/")
data = re.search(r"window\.__PRELOADED_STATE__ = (.*)", tor_r.text)
data = json.loads(data.group(1))

def find_images(d):
    if isinstance(d, dict):
        for k, v in d.items():
            if k == "image":
                yield v
            else:
                yield from find_images(v)
    if isinstance(d, list):
        for v in d:
            yield from find_images(v)

images = []

for img in find_images(data):
    if img["url"]:
        images.append("https://www.thestar.com" + img["url"])

images = images[4:14]

#zip file to concurrently loop news and headlines in the django templates inside my index.html file

toronto = zip(toi_news, images)

def index(req):
    return render(req, 'news/index.html', {'toi_news':toi_news, 'ht_news': ht_news, 'images': images, 'toronto': toronto})

没关系,我自己找到了解决方案。我只需要在 views.py 文件第 79 行的 toronto 变量中的 zip() 函数周围添加一个 list() 函数。希望这对某人有所帮助!