我已經在 python 中存盤了一些資料,現在我想在 django 中顯示它,我該怎么做?
animeUrl = "https://api.jikan.moe/v4/top/anime"
animeResponse = requests.get(animeUrl).json()
def topAnime():
for idx, video in enumerate(animeResponse['data']):
animeUrl = video['url']
title = video['title']
status = video['status']
type = video['type']
images = video['images']['jpg']['image_url']
#if status == "Currently Airing":
print (idx 1,":",animeUrl, ":", status, ":", title, ":", type, ":", images)
topAnime()
這是我存盤的資料,現在我想在網站上顯示它,我該怎么做?我是 django 的新手,我正在尋找一些建議
我試過使用模板,但沒有用
uj5u.com熱心網友回復:
如果您是新手,我強烈建議您按照教程構建您的第一個專案,它可以幫助您掌握一些關鍵概念。您可以在第三部分找到您的解決方案。
但是,回答你的問題:
在您應用的 views.py 中:
from django.shortcuts import render
import requests
def get_animes(request):
url= "https://api.jikan.moe/v4/top/anime"
response= requests.get(url).json()
return render(request, 'animes.html', { 'data': response['data']})
在您應用的 urls.py 中:
from django.urls import path
from . import views
urlpatterns = [
path('animes/', views.get_animes, name='animes'),
]
在您的 animes.html 檔案中:
{% for obj in data %}
{{ obj.url }}
<br>
{{ obj.title }}
<br>
{{ obj.status }}
<br>
{{ obj.type }}
<br>
{{ obj.jpg.image_url }}
<br>
<br>
{% endfor%}
在你的根 urls.py 中:
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myApp.urls')),
]
最后,運行您的開發服務器:
python manage.py runserver
打開瀏覽器并向您的 URL 發送請求:
http://localhost:8000/animes/
uj5u.com熱心網友回復:
這里回答了這個問題: How to pass data to a template in Django?
為了在 django 中顯示從 url 到 html 檔案的資料,有兩種方法
方法一:渲染模板連同資料 Django Templates
如何在專案中使用它:Render Html Pages in django
您可以借助以上兩個鏈接輕松設定 jinja 語法
方法二:使用django Rest Framework Django Rest Framwork
如果您已經使用過 api 并使用 java 腳本發送 ajax 請求,則更喜歡此方法
方法示例代碼結構 - 1:main.py
from django.shortcuts import render
animeUrl = "https://api.jikan.moe/v4/top/anime"
animeResponse = requests.get(animeUrl).json()
def topAnime():
for idx, video in enumerate(animeResponse['data']): # z [data] wyciaga mi nastepujace rzeczy ktorze sa pod spodem
animeUrl = video['url']
title = video['title']
status = video['status']
type = video['type']
images = video['images']['jpg']['image_url']
#if status == "Currently Airing":
print (idx 1,":",animeUrl, ":", status, ":", title, ":", type, ":", images)
topAnime()
def requestSender(request):
return render(response, "index.html", data=topAnime())
索引.html
<body>
<p> {{ data }} </p>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/536365.html
