[英]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.