如何在 Django 中使用 RESTful API

How to Use RESTful APIs with Django

我一直在尝试将使用 Django-rest 框架开发的 REST API 与另一个 Django 网络应用程序集成。但是坚持将 JSON 数据传递到前端。我将不胜感激任何帮助。这是我各自的文件。

我在 views.py 文件上尝试了两种不同的 urls,一种是 AWS API 网关 API,使用时不会抛出任何错误,但不会显示数据在前端。

AWS API JSON 对象类似于 {'key': 'value'} 的数据。虽然它只包含一个对象

views.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 时,我收到类似“the JSON object must是 str、bytes 或 bytearray,而不是 list" JSON 数据,其中对象类似于 [{key: value},{key:value}, ...] Table body 已更改因此。

前端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)