django - 如何在 Django 后端使用 Angular 数据表
问题描述
我正在尝试将 Datables 与 Django 一起使用,但我无法弄清楚如何以正确的形式获取数据。Django 的 rest API 正在返回一个对象,但 Angular Datatables 需要一个 JSON 文件,那么我该如何实现这个结果呢?
这是我尝试过的:
HTML:
<table datatable class="row-border hover">
<thead>
<tr class="header">
<th class="date">Id</th>
<th class="date">Nom</th>
<th class="societe">Email</th>
<th class="evenements">Date d'inscription</th>
<th class="facturePDF">Actif</th>
</tr>
</thead>
<tbody *ngIf="persons?.length != 0">
<tr *ngFor="let item of Users;let index=index">
<td class="text-monospace pt-3 pl-4">
{{item?.id}}
</td>
<td class="text-monospace pt-3 pl-4">
{{item?.name}} {{item?.lastname}}
</td>
<td class="text-monospace pt-3 pl-4">
{{item?.email}}
</td>
<td class="text-monospace pt-3 pl-4">
{{item?.date_joined.slice(0,10)}}
</td>
<td class="text-monospace pt-3 pl-4">
{{item?.is_active}}
</td>
</tr>
</tbody>
<tbody *ngIf="Users?.length == 0">
<tr>
<td colspan="3" class="no-data-available">No data!</td>
</tr>
<tbody>
</table>
admin.component.ts:
ngOnInit() {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 2
};
this.GetUsers();
}
GetUsers(){
this.ApiService.list_users(this.page).subscribe(
data => {
this.Users = this.Users.concat(data);
},
error=>{
console.log(error);
}
)
}
“list_users”函数调用 Django 从数据库中检索数据:
@api_view(['GET','POST','DELETE'])
def list_annonces(request):
if request.method == 'GET':
annonces = Annonces.objects.all().order_by('-id')
count = Annonces.objects.count()
try:
page = int(request.GET.get('page'))
except Exception:
page = 1
limit = count
offset = (page-1) * 10
annonces_data = AnnonceSerialize(annonces.all()[offset:limit], many=True)
return Response(annonces_data.data, status.HTTP_200_OK)
```
解决方案
你可能想要JSON.stringify(<object_from_django>)
。
推荐阅读
- ruby-on-rails - 具有 has_many 的表单中的列组件不起作用
- java - 在 lambda java 中将变量更改出 lambda 表达式范围
- ios - Swift 编译错误
- regex - oracle regex_replace
- node.js - 如何直接从 angular component.html 调用节点 api
- proxy - 如何获取代理服务器ip
- java - 在 Parse 中注册显示错误:com.parse.ParseUser.signUpInBackground()' 在空对象引用上
- java - Camel-Undertow 不适用于 SSL 配置:
- android - 如何更改 com.mancj.materialsearchbar.MaterialSearchBar 中的文本颜色
- oracle - BEGIN END 块 PL/SQL 中的 WITH 子句行为