【问题标题】:Connect Angular Frontend to Django View将 Angular 前端连接到 Django 视图
【发布时间】:2021-12-01 11:46:54
【问题描述】:

我有一个基本的 django 应用程序,它只需将 excel 文件上传到 oracle 数据库。我创建了一个 python 类(上传器)来对文件进行一些完整性检查并上传到数据库。

我已经成功地在 Django 模板中使用 HTML 创建了一个 UI,效果很好。

但是,我想将前端迁移到 Angular 前端。

我已经创建了 Angular 应用程序,但我目前正在努力了解如何将前端连接到 django。 在线研究后,他们建议使用模型、序列化程序,但因为我通过独立的 python 类进行上传,我不知道如何使用这种方法连接两者。我假设我必须使用 HttpClient 以某种方式连接到这个视图?

任何帮助将不胜感激。谢谢

上传/views.py

def clickToUpload(request):
if request.method == 'POST':
    if 'form' in request.POST:
        try:
            upload_instance = uploader(request.FILES['file'], request.POST['date'])
            _ = upload_instance.run_process('File', update_log=True)
            upload_message= "Success"
        except Exception as e:
            upload_message = 'Error: ' + str(e)

     return render(request, 'Upload/upload.html', {'upload_message':upload_message})

更新 视图.py

from rest_framework.response import Response
from rest_framework import status

def clickToUpload(request):
  if request.method == 'POST':
    if 'form' in request.POST:
        try:
            upload_instance = uploader(request.FILES['file'], request.POST['date'])
            _ = upload_instance.run_process('File', update_log=True)
            upload_message= "Success"
            return Response(upload_message, status=status.HTTP_201_CREATED)
        except Exception as e:
            upload_message = 'Error: ' + str(e)
            return Response(upload_message , status=status.HTTP_400_BAD_REQUEST)

file-upload.service.ts

export class FileUploadService {
  DJANGO_SERVER: string = "http://127.0.0.1:8000";
  constructor(private http:HttpClient) { }
  public upload(data: any) {
    return this.http.post<any>(`${this.DJANGO_SERVER}/lcr-upload/upload/`, data);
  }
}

上传.component.ts

constructor(private fileUploadService: FileUploadService) { }

  ngOnInit(): void {
  }

  onChange(event: any) {
    this.file = event.target.files[0];
    console.log("This file is: " + this.file)
  }

  onUpload() {
    this.loading = !this.loading;
    console.log(this.file);
    this.fileUploadService.upload(this.file).subscribe(
      (event: any) => {
        if (typeof (event) === 'object') {
          this.shortLink = event.link;
          this.loading = false;
          console.log("OnUploadClicked")
        }
      }
    )
  }
}

upload.component.html

    <div class="input-group">
        <input class="form-control" type="file" (change)="onChange($event)">
        <!-- <span><button (click)="onUpload()" class="btn btn-dark">Upload</button></span> -->
    </div>
    <br>
    <div class="input-group" style="font-size: 18px">
        <mat-form-field appearance="outline">
            <mat-label>Choose a Date</mat-label>
            <input matInput [matDatepicker]="picker">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
    </div>
    <div class="input-group" style="font-size: 18px">
        <button class="btn btn-success" (click)="onUpload()">Upload</button>
    </div>

【问题讨论】:

    标签: python django angular


    【解决方案1】:

    因此,您必须将当前的clickToUpload 修改为 Django 中的 API 端点,该端点基本上将您的文件作为表单数据接收。它不应该将视图返回到您的模板。在 Angular 中,您将在用户上传文件时调用该 API 端点。

    示例 Django 文件上传 API (views.py):

    from rest_framework.response import Response
    from rest_framework import status
    
    def clickToUpload(request):
      if request.method == 'POST':
        if 'form' in request.POST:
            try:
                upload_instance = uploader(request.FILES['file'], request.POST['date'])
                _ = upload_instance.run_process('File', update_log=True)
                upload_message= "Success"
                return Response(upload_message, status=status.HTTP_201_CREATED)
            except Exception as e:
                upload_message = 'Error: ' + str(e)
                return Response(upload_message , status=status.HTTP_400_BAD_REQUEST)
    

    创建 API 后,您需要在 Angular 中创建一个服务,该服务调用端点并传递您上传的表单数据。有一个很好的教程here

    【讨论】:

    • 谢谢。您的建议是否需要创建数据库模型?
    • 是的,因为您需要保存到该模型,对吗?
    • 我们创建了一个标准的 python 类,它使用 sqlalchemy 来写入/上传到数据库。我们发现这更快,并且在当前设置中(在 Django 端有一个 html 模板)我们的上传按钮成功写入数据库
    • 如果您当前的代码有效,只需将您的返回转换为响应而不是视图,那么您不必使用模型或序列化程序。如果您不确定我的意思,我可以更新我的答案以反映这一点。
    • 如果您能更新您的回复,那就太好了。我对 Angular 还很陌生,所以很难建立联系。感谢您迄今为止的帮助
    猜你喜欢
    • 2017-09-18
    • 2016-07-20
    • 2019-11-14
    • 1970-01-01
    • 2016-11-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多