首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Django后端使用Angular Datatables

如何在Django后端使用Angular Datatables
EN

Stack Overflow用户
提问于 2020-09-02 18:50:37
回答 2查看 84关注 0票数 0

我试图在Django中使用Datables,但我不知道如何以正确的形式获取数据。Django的rest API返回一个对象,但是Angular Datatables需要一个JSON文件,那么我如何实现这个结果呢?

这是我尝试过的:

HTML:

代码语言:javascript
运行
复制
<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:

代码语言:javascript
运行
复制
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从数据库中检索数据:

代码语言:javascript
运行
复制
@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)
代码语言:javascript
运行
复制
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-03 00:20:45

好吧,如果任何人都面临同样的问题,下面是我如何解决它的:

在您的组件文件中添加以下代码:

代码语言:javascript
运行
复制
class Person {
  id: number;
  firstName: string;
  lastName: string;
}

export class AdminComponent implements OnInit {
  dtOptions: DataTables.Settings = {};
  persons: Person[];
  private dtTrigger: Subject<Users> = new Subject();

 constructor(private activatedRoute: ActivatedRoute, private ApiService : ApiService,
    private Authservice: AuthService, private approuter: Router, private MatDialog : MatDialog,
    private config: ConfigService, private http: HttpClient) {}

ngOnInit(): void {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10
    };
    this.http.get<any>(this.Authservice.getApiUrl() + 'users/list/?page=1')
      .subscribe(persons => {
        this.persons = persons;
        console.log("Persons == ", this.persons);
        // Calling the DT trigger to manually render the table
        this.dtTrigger.next();
      });
  }

  ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();
  }

}

对于模板文件,我需要遍历新的persons对象,而不是用户数组:

代码语言:javascript
运行
复制
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" 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 persons;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="persons?.length == 0">
                <tr>
                <td colspan="3" class="no-data-available">No data!</td>
                </tr>
            <tbody>
        </table>
票数 0
EN

Stack Overflow用户

发布于 2020-09-02 21:38:30

您可能想要使用JSON.stringify(<object_from_django>)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63703965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档