[英]How do i display my views.py output on a template
这是我的 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>
我已经在模板上添加了完整的代码
请在您的网页中使用 {{headline}},因为在您的上下文中您传递的是“标题”。 我看到它有很多数据,所以你也可以在 Django 模板中使用 for 循环。 像下面....
{% for headline in headline %}
{{headline}}
{% endfor %}
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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.