简体   繁体   English

如何在 Django 中使用 RESTful API

[英]How to Use RESTful APIs with Django

I have been trying to integrate a REST API developed using Django-rest framework with another Django web app.我一直在尝试将使用 Django-rest 框架开发的 REST API 与另一个 Django Web 应用程序集成。 But stuck in passing JSON data into the front-end.但坚持将 JSON 数据传递到前端。 I would appreciate any help.我将不胜感激任何帮助。 Here are my respective files.这是我各自的文件。

I have tried two different urls on views.py file, one is AWS API Gateway API, when used no errors are thrown but data is not displayed in front-end.我在 views.py 文件上尝试了两种不同的 url,一种是 AWS API Gateway API,使用时不会抛出错误但前端不显示数据。

AWS API JSON data where object is like {'key': 'value'}. AWS API JSON 数据,其中对象类似于 {'key': 'value'}。 it contains only one object though虽然它只包含一个对象

views.py视图.py

def ClientList(request):
      response = requests.get('A URL')
      client_data = response.json()
      return render(request, 'clients/client_list.html', context=client_data)

When I change the url in views.py for django-rest framework API then I get an error like " the JSON object must be str, bytes or bytearray, not list " JSON data where objects are like [{key: value},{key:value}, ...] Table body was changed accordingly.当我为 django-rest 框架 API 更改 views.py 中的 url 时,我收到一个错误,如“ JSON 对象必须是 str、bytes 或 bytearray,而不是列表”JSON 数据,其中对象类似于 [{key: value},{ key:value}, ...] 表体已相应更改。

FrontEnd HTML前端 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>

Modified view.修改视图。 The returned json list is converted into dictionary.返回的 json 列表被转换为字典。 And it worked.它奏效了。 Note: dictionary key need to match in html too.注意:字典键也需要在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM