Показать данные из API на Django tempalte - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь показать извлеченные данные в API для шаблона Django.

Вот то, что я попробовал на home.html

<h1>Title: {{data.title}}</h1>

Вот мой views.py, который получает данные от services.py

class IndexData(TemplateView):
    def get(self, request):
        article_data = services.get_data()
        return render(request, 'pages/home.html', article_data)

Вот services.py

def get_data(title, url, description, body, datePublished):
  url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI'
    params = {"autoCorrect": "true", "pageNumber": "1", "pageSize": "10", "q": "police", "safeSearch": "true" }
    headers = {...}
    r = requests.get(url, headers=headers, params=params)
    data = r.json()
    article_data = {'data': data['value']}
    return article_data

Возвращенный json - это

{   "_type":"all",
    "didUMean":"",
    "totalCount":2923,
    "relatedSearch":[
       "coronavirus",
       "new york",
       "post",
       "getty",
       "times",
       "china",
       "council",
       "shares",
       "americans",
       "pandemics",
       "prime",
       "19 crisis"

 ],
    "value":[      
      {         
          "title":"COVID-19 And The Failure Of Populism",
          "url":"https://www.forbes.com/sites/riskmap/2020/04/02/covid-19-and-the-failure-of-populism/",
          "description":"Populist presidents, reliant on their need to constantly convey positive messaging that bolsters their support, have struggled to take the decisive, forward-looking action that the coronavirus crisis demands.",
          "body":").\nHow will the pandemic play out in these countries?\nSteering countries through the pandemic and an eventual recovery will then be the responsibility of leaders who will have lost credibility, as well as the veneer of their all is well message. The narrative that allowed people in certain countries to latch on to something they approved of in their leader (the economy is doing well, the corruption of previous regimes was intolerable, there was no alternative, etc) while disregarding all the caveats of things they disliked, may now give way to harsher judgement. Hopefully, if there is any silver lining, the public might start trusting experts and reliable sources of information again, and will begin to question their leaders more actively.\nEither way, populist leaders like Trump, AMLO, and Bolsonaro will each have demonstrated a great inability to manage any criticism, no matter who it comes from or how constructive it might be. On the contrary, they seem to double-down",
     "keywords":"",
     "language":"en",
     "isSafe":true,
     "datePublished":"2020-04-02T11:00:00",
     "provider":{
        "name":"forbes"

 },
          "image":{
             "url":"https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fdam%2Fimageserve%2F99b82bcbe089442095046d2dbb9ecbf9%2F0x0.jpg%3Ffit%3Dscale",
            "height":800,
        "width":1200,
        "thumbnail":"https://rapidapi.contextualwebsearch.com/api/thumbnail/get?value=37416569554313599",
        "thumbnailHeight":200,
        "thumbnailWidth":300,
        "base64Encoding":null,
        "name":null,
        "title":null,
        "imageWebSearchUrl":null

}

}

Что я пропустил?

Ответы [ 2 ]

0 голосов
/ 16 апреля 2020

Просто сделай в своем шаблоне

{{ article_data.value.0.title }}
0 голосов
/ 16 апреля 2020

value ключ в ответе - список. Вам также нужно получить доступ к его первому элементу.

Возможно, это должно сработать, в service.py вы можете изменить строку, в которой вы объявляете article_data, на:

article_data = {'data': data['value'][0]}

Ответ следующий вопрос из комментария, для datePublished, поскольку он того же уровня, что и title, вы можете просто использовать data.datePublished в своем шаблоне.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...