首页 > 解决方案 > 将数据上传到 Django REST API 时没有提交文件错误

问题描述

我使用 angular/typescript 将某种形式的数据上传到我的 Django REST API。有了数据,一切都是正确的,因为我可以记录整个表格并取回所有数据。但是当涉及到上传数据时,我得到了这个错误:

{src: ["No file was submitted."], tag: ["This field is required."]}

所以不知何故它无法识别我的数据,因为我实际上是在提交数据。

前端代码

上传服务

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'multipart/form-data'})
};

...

  uploadPost(src: File, tag: string) {
    return this.http.post<any>(`{this.url}/posts/`, {src, tag}, httpOptions);
}

post.page

  ngOnInit() {

  this.storage.get('image_data').then((imageFile) => {
      console.log(imageFile)
      this.categoryForm.patchValue({
        'image': this.storage.get('image_data')
      });
    });

        this.categoryForm = new FormGroup({

          'category': new FormControl('', Validators.compose([
            Validators.maxLength(25),
            Validators.minLength(1),
            Validators.required
          ])),

          'image': new FormControl(null),
        });

apiSubmit() {
console.log('logged')
console.log(this.f.image);
this.submitted = true;
if (this.categoryForm.invalid) {
  return;
}
this.isLoading = true;
this.loadingEl.present();
this.uploadService.uploadPost(
  this.f.image,
  this.f.category
    )
.pipe(tap(x => this.loadingEl.dismiss())
)
.subscribe(
  data => {
    this.router.navigate(['one']);
  },
  error => {
    this.error = error;
  }
);
}

姜戈:

模型.py

   class Post(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts', on_delete=models.CASCADE)

        src = models.ImageField(blank=False, null=False, editable=False, upload_to=utils.get_file_path,)
        date_posted = models.DateTimeField(auto_now_add=True, editable=False)
        last_modified = models.DateTimeField(auto_now=True)
        when = models.FloatField(blank=True, null=True)
        lock = models.BooleanField(default=False)
        des = models.CharField(
            max_length=100,
            validators=[
                RegexValidator(
                    regex='^[-_a-zA-Z0-9\.]+$',
                    message='only 1 to 20 characters and only letters, numbers, point, minus and underscore are allowed',
                ),
            ])

视图.py

      @swagger_auto_schema(request_body=doc_serializer.CreatePostDummy, responses={201: PostSerializer})
            def create(self, request, *args, **kwargs):
                """permission required: authenticated. Note: the schema is not json it's multipart"""
                return super().create(request, *args, **kwargs)

doc_serializers.py

    class CreatePostDummy(serializers.HyperlinkedModelSerializer):
        `enter code here`user = serializers.HyperlinkedRelatedField(required=False, read_only=True, view_name='user-detail')
        src = serializers.CharField(required=True, help_text='Not Char but image upload field')

标签: pythondjangotypescriptdjango-rest-framework

解决方案


推荐阅读