将数据上传到Django REST API时没有文件提交错误

时间:2019-12-13 10:06:32

标签: python django typescript django-rest-framework

我正在使用angular / typescript,在这里我将数据形式上传到Django REST API。有了数据,所有数据都是正确的,因为我可以记录我的整个表格,然后取回所有数据。但是,在上传数据时,出现了以下错误:

  

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

以某种方式它无法识别我的数据,因为我实际上正在提交数据。

前端代码

upload.service

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;
  }
);
}

Django:

models.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',
                ),
            ])

view.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')

0 个答案:

没有答案