如何在Django中将JSON数组正确传递给HTML模板?

时间:2019-06-11 22:04:59

标签: python json django

我当然想以“我是新手”开头这个问题,我已经在Python和Django上工作了很短的时间,但是在将JSON数组传递到HTML模板时遇到了问题。返回的数组与此类似;

[
  {
    "id": "Tex"
    "color": "Purple"
   }
]

实际数组要大得多,但这将适用于我的示例。 这是我的表格。

class PlayerForm(forms.Form):
id = forms.CharField(max_length=100)

def search(self):
    result = {}
    id = self.cleaned_data['id']
    endpoint = 'https://api.littleleague.com/players/v1/path/{ID}/playertracking'
    url = endpoint.format(ID=id)
    headers = {'Authorization': settings.E_AUTH, 'Accept': "*/*", 'accept-encoding': "gzip, deflate", 'Connection': "keep-alive",}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:  # SUCCESS
        result = response.json()
        result['success'] = True
    else:
        result['success'] = False
        if response.status_code == 404:  # NOT FOUND
            result['message'] = 'No entry found for "%s"' % id
        else:
            result['message'] = 'The API is not available at the moment. Please try again later.'              
    return result

这是我的观点

def player(request):
search_result = {}
if 'id' in request.GET:
    form = PlayerForm(request.GET)
    if form.is_valid():
        search_result = form.search()
else:
    form = PlayerForm()
return render(request, 'app/player.html', {'form': form, 'search_result': search_result})

这是我的HTML模板:

    {% extends "app/layout2.html" %}

{% block content %}
<h2>Players & Colors</h2>

<form method="get">
    {{ form.as_p }}
    <button type="submit">search</button>
</form>

<hr>
{% if search_result.success %}
<h1>Success</h1>
{% else %}
<p><em>{{ search_result.message }}</em></p>
{% endif %}

{% endblock %}

如您所知,我什至没有尝试传递数据,但是在点击提交时仍然收到错误消息

“列表索引必须是整数或不是str的切片”

我相信错误在我的表单内@ result = response.json()我过去曾做过这项工作,但结果不是数组。

这是回溯:

    Traceback:

File "C:\Users\admin\source\repos\llbb\llbbp\env\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\admin\source\repos\llbb\llbbp\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\admin\source\repos\llbb\llbbp\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\source\repos\llbb\llbbp\app\views.py" in disclosure
  74.             search_result = form.search()

File "C:\Users\admin\source\repos\llbb\llbbp\app\forms.py" in search
  100.             result['success'] = True

Exception Type: TypeError at /player/
Exception Value: list indices must be integers or slices, not str

0 个答案:

没有答案