【问题标题】:How do i display my views.py output on a template如何在模板上显示我的 views.py 输出
【发布时间】:2019-12-24 06:35:00
【问题描述】:

这是我的观点.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>

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

【问题讨论】:

标签: python django beautifulsoup


【解决方案1】:

请在您的网页中使用 {{headline}},因为在您的上下文中您传递的是“标题”。 我看到它有很多数据,所以你也可以在 django 模板中使用 for 循环。 如下图......

  {% for headline in headline %}

  {{headline}}

  {% endfor %}

【讨论】:

  • 你能显示你的模板代码吗..还请检查你是否在正确的页面上呈现。
  • 我已将其添加到主帖
  • 能否在循环外使用上下文行,然后尝试。 def print_headlines(request,response_text): soup = BeautifulSoup(response_text, 'lxml') headings = soup.find_all(attrs={"itemprop": "headline"}) context = { "headline": headers } return render(request, 'home/maroweb.html',上下文)
  • 什么都没变,还是一样
  • 您是否检查过数据是否来自您的过滤器?
【解决方案2】:
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 %}

【讨论】:

  • 它不起作用,views.py 甚至没有在终端上显示输出。我收到 TypeError: print_headlines() 丢失。 1 个必需的位置参数:'response_text'
  • @user12075410 您是否像调用其他函数一样调用 Django 视图?这不是它的工作方式..您必须设置 urlpatterns 并在此处提及您的 print_headlines 视图才能使其正常工作。请再看一遍 Django 的文档。此外,您收到错误是因为您的函数print_headlines 需要两个参数,即requestresponse_text,而您只传递了一个。
  • 好吧,我不知道。我将添加 urlpatterns
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 2014-12-03
  • 2021-08-21
  • 2015-03-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
相关资源
最近更新 更多