gpt4 book ai didi

Python/Django - 模板中的提取请求中未出现数据

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:01 26 4
gpt4 key购买 nike

我是 python 新手,正在尝试从导入的新闻 api 中提取数据,但是,即使我没有收到任何可见的错误,它似乎也没有显示在模板中。我正在尝试使用 MVC 框架来组织我的代码

views.py开始

future 导入unicode_literals

import json
import logging
import requests
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views import generic
from newsapi import NewsApiClient

from .forms import UserProfileCreationForm
from .models import Animals

def news_list(request):
newsapi = NewsApiClient(api_key='123')
all_articles = newsapi.get_everything(
q='animals',
sources='bbc-news,national-geographic, new-scientist, reddit-r-all',
from_param='2018-09-29',
to='2018-09-22',
language='en',
sort_by='relevancy')['articles']
context = {'articles': all_articles,
'type': str(type(all_articles)),
'name': 'Someone'}

template = loader.get_template('home.html')

return HttpResponse(template.render(context, request))

然后urls.py

from django.conf.urls import url, include
from . import views

urlpatterns = [
url(r'^$', views.news_list, name="news_list"),
]

这里还有项目文件夹中的urls.py,不确定它是否有帮助

from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView


urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^users/', include('dangerzone.urls')),
url(r'^users/', include('django.contrib.auth.urls'))
]

最后是模板

base.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
{% block title %}
Python App
{% endblock title %}
</title>
</head>
<body>
<main>
{% block content %}

{% endblock content %}
</main>
</body>
</html>

home.html

{% extends 'base.html' %}

{% block content %}

<h2>Latest News</h2>
<ul>
{% for article in articles %}
<li>{{ article.source }}</li>
<li>{{ article.author }}</li>
<li>{{ article.title }}</li>
{% endfor %}
</ul>
{% endblock content %}

如果需要更多信息,请告诉我。

到目前为止我已经尝试过:

  1. 将网址地址从 r'^$' 更改为 ''
  2. 不使用 HttpResponse 进行导入,如下所示:

     def news_list(request):
    newsapi = NewsApiClient(api_key='123')
    all_articles = newsapi.get_everything(
    q='animals',
    sources='bbc-news,national-geographic, new-scientist, reddit-r-all',
    from_param='2018-09-29',to='2018-09-22',
    language='en',
    sort_by='relevancy',
    page=2)['articles']
    return render(request, 'home.html', {'articles' : all_articles})

最佳答案

您能告诉我们您的 Python/Django 版本吗?

另外,如果我没记错的话,你的

template = loader.get_template('home.html')

return HttpResponse(template.render(context, request))

在您的 news_list() 函数之外。

关于Python/Django - 模板中的提取请求中未出现数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52628944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com