【问题标题】:How to display json value in django template?如何在 django 模板中显示 json 值?
【发布时间】:2016-09-01 07:47: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})

【问题讨论】:

  • 能否修复代码格式以提高可读性?
  • 你要写book.html文件。
  • 跟着 django-tutorial 你会发现的。

标签: javascript python json django


【解决方案1】:

那个“js”应该是一个python dict而不是json对象。您可能需要:

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

然后就可以使用book.html模板中的变量了。

【讨论】:

  • Requests 从json() 方法返回一个 Python 字典。
猜你喜欢
  • 1970-01-01
  • 2019-04-18
  • 2014-11-12
  • 2017-09-28
  • 2017-11-13
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多