如何在django模板中显示json值

How to display json value in django template?

本文关键字:显示 json django      更新时间:2023-09-26

这是我的View.py代码…

import requests 
from django.http import HttpResponse 
from django.shortcuts import render import json 
def book(request):
    if request.method == 'POST':
        r = requests.post('http://api.railwayapi.com/cancelled/date/01-09-2016/apikey/mezxa1595/', params=request.POST)
        book=r.json()
    else:
        r = requests.get('http://api.railwayapi.com/cancelled/date/01-09-2016/apikey/mezxa1595/', params=request.GET)
        book=r.json()
        js=json.dumps(book)
    if r.status_code == 200:
        return render(request,'book.html', {'js':js})
    return HttpResponse('Could not save data')

和问题是如何在Html中显示return render(request,'book.html', {'js':js}) ?

该"js"应该是python字典而不是json对象。您可能需要:

return render(request,'book.html', {'js': json.loads(js)})

则可以使用book.html模板中的变量