python - 将数据上传到 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')
解决方案
推荐阅读
- git - IntelliJ - - 如何应用整个文件作为更改?
- serialization - 在 Scheme 中,如何将记录 (srfi-9) 保存到文件中(将它们序列化到文件中),然后再将它们读回?
- reactjs - Redux 表单,针对特定字段清除和休息,反应 JS
- python - 使用 pandas 选择一组特定的分组数据框
- testing - 如何在 TestCafe 中计算以前的兄弟姐妹?
- python - 如何在命令提示符下安装 pip?“启动器中的致命错误”
- .net - 尝试在 .net 中使用 Lotus Notes IDXLExporter 会导致 System.OutOfMemoryException
- python - 如何从 mp3 文件中获取元数据(流派、艺术家)?
- discord - Discord bot ctx 被显示为参数
- python - 如何更改感兴趣区域的 pyplot 背景颜色?