如何在模板上显示views.py输出

时间:2019-12-24 06:35:00

标签: python django beautifulsoup

这是我的views.py

from django import template
from django.shortcuts import render
import requests
from bs4 import BeautifulSoup


def print_headlines(request,response_text):
    soup = BeautifulSoup(response_text, 'lxml')
    headlines = soup.find_all(attrs={"itemprop": "headline"})
    for headline in headlines:
        print(headline.text)
        context = {
            "headline": headline
        }
    return render(request, 'home/maroweb.html', context)


url = 'https://inshorts.com/en/read'
response = requests.get(url)
print_headlines(response.text)

然后在我的网页上,我使用{{headlines}}显示结果,但没有显示模板代码

然后在我的网页上,我使用{{headlines}}显示结果,但没有显示模板代码

{% extends "base.html" %}
{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block content %}
 {{ self.banner_title }}

{% for headline in headline %}

  {{headline}}

  {% endfor %}


 {% endblock %}

</body>
</html>

我已经在模板上添加了完整的代码

2 个答案:

答案 0 :(得分:0)

请在您的网页中使用{{headline}},因为在您的上下文中,您正在传递“标题”。 我看到它有很多数据,因此您也可以在Django模板中使用for循环。 像下面一样。...

  {% for headline in headline %}

  {{headline}}

  {% endfor %}

答案 1 :(得分:0)

from django import template
from django.shortcuts import render
import requests
from bs4 import BeautifulSoup


def print_headlines(request,response_text):
    soup = BeautifulSoup(response_text, 'lxml')
    headlines = soup.find_all(attrs={"itemprop": "headline"})
    context = {
        "headlines": headlines
    }
    return render(request, 'home/maroweb.html', context)

url = 'https://inshorts.com/en/read'
response = requests.get(url)
print_headlines(response.text)

您的模板将是:

{% for headline in headlines %}
    {{ headline }}
{% endfor %}