【问题标题】:Consuming JSON into django view将 JSON 消费到 django 视图中
【发布时间】:2016-03-30 22:45:06
【问题描述】:

我想在我的 API 中使用我使用 django_rest_framework 创建的 api。我想使用在我的视图和模板中生成的 json。这是我的 json -

[
{
"url": "http://127.0.0.1:8000/app/clubs/1/persons/",
"id": 1,
"club_name": "club1",
"persons": [
    1,
    2
]
},
{
"url": "http://127.0.0.1:8000/app/clubs/2/persons/",
"id": 2,
"club_name": "club2",
"persons": [
    1,
    4
]
},
]

我想像这样在我的模板中使用它 -

{% for c in club %}
  {{c.url}}{{c.club_name}}  
{% endfor %}

我尝试了以下视图,分别获取 unicode 字符串,但 urlclub_name 将在不同的上下文中 -

def clubs(request):
  data = requests.get('http://127.0.0.1:8000/app/clubs/').json()
  count=0
  for i in data:
    count+=1
  g=[]
  identity=[]
  for j in range(count):
    g.append(data[j]['club_name'])
    identity.append(data[j]['url'])

  context = RequestContext(request, {
    'club_name': g,'count':count,'url':identity,
  }) 
  return render_to_response('imgui/clubs.html', context)   

还有其他方法可以做我想做的事吗?

【问题讨论】:

    标签: python json django django-templates django-views


    【解决方案1】:

    您在模板中需要的club 在您看来就是data

    def clubs(request):
        data = requests.get('http://127.0.0.1:8000/app/clubs/').json()
    
        context = RequestContext(request, {
            'club': data,
        })
    
        return render_to_response('imgui/genres.html', context)
    

    与问题本身无关,但有一些提示:

    • 这个循环:

      count=0
      for i in data:
          count+=1
      

      相当于:count = len(data)

    • 这个循环:

      for j in range(count):
          g.append(data[j]['club_name'])
          identity.append(data[j]['url'])
      

      最好写成:

      for c in data:
          g.append(c['club_name'])
          identity.append(c['url'])
      

    【讨论】:

      猜你喜欢
      • 2016-03-22
      • 2020-05-13
      • 2015-09-18
      • 2020-05-21
      • 2017-08-03
      • 2019-08-11
      • 1970-01-01
      • 2020-07-16
      • 2013-03-13
      相关资源
      最近更新 更多