[英]How to Use RESTful APIs with Django
我一直在尝试将使用 Django-rest 框架开发的 REST API 与另一个 Django Web 应用程序集成。 但坚持将 JSON 数据传递到前端。 我将不胜感激任何帮助。 这是我各自的文件。
我在 views.py 文件上尝试了两种不同的 url,一种是 AWS API Gateway API,使用时不会抛出错误但前端不显示数据。
AWS API JSON 数据,其中对象类似于 {'key': 'value'}。 虽然它只包含一个对象
视图.py
def ClientList(request):
response = requests.get('A URL')
client_data = response.json()
return render(request, 'clients/client_list.html', context=client_data)
当我为 django-rest 框架 API 更改 views.py 中的 url 时,我收到一个错误,如“ JSON 对象必须是 str、bytes 或 bytearray,而不是列表”JSON 数据,其中对象类似于 [{key: value},{ key:value}, ...] 表体已相应更改。
前端 HTML
<table class="table data-list-view">
<thead>
<tr>
<th></th>
<th>NAME</th>
<th>EMAIL</th>
<th>MOBILE</th>
<th>ADDRESS</th>
<th>ROLE</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
{% for client in client_data %}
<tr>
<td></td>
<td class="product-name">{{client.UserId}}</td>
<td class="product-category">{{client.Height}}</td>
<td class="product-category">{{client.Income}}</td>
<td class="product-category">{{client.Age}}</td>
<td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
修改视图。 返回的 json 列表被转换为字典。 它奏效了。 注意:字典键也需要在 html 中匹配。
def ClientList(request):
response = requests.get('http://127.0.0.1:8000/clients/')
client_data = response.json()
context = {'client_data': client_data}
return render(request, 'clients/client_list.html', context)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.