问题描述
我用axios更新了我的模型,文件字段导致了一些错误。我使用PATCH方法进行更新,这意味着我只能包含一个要更改的字段。例如,当我仅发布新图片时,我的图片字段将被更新,而我可以将其他字段留空。因此,仅更新我的图像字段即可。但是现在当我尝试仅更新我的姓名字段时,会发生下一个错误。
接下来的事情是,当我同时更新我的图像字段和名称字段时,这也起作用并且我的模型得到更新。这确实是一个令人困惑的错误,但我希望有人知道在这里可能导致问题的原因。预先感谢!
我的表单处理方法:
handleFormSubmit = (event) => {
event.preventDefault();
let form_data = new FormData();
form_data.append('name',event.target.elements.name.value);
form_data.append('email',event.target.elements.email.value);
form_data.append('location',event.target.elements.location.value);
form_data.append('sport',this.state.sport);
form_data.append('image',this.state.file.file,this.state.file.file.name);
console.log(form_data.image);
const profileID = this.props.token
let url = `http://127.0.0.1:8000/api/profile/${profileID}/update`
axios.patch(url,form_data,{
headers: {
'content-type': 'multipart/form-data'
}
})
.then(res => console.log(res))
.catch(error => console.err(error));
}
在前端,我也使用ReactJS,对于Form,也使用Ant Design Form,但这没关系
控制台中的文件对象: screenshot of console
DRF:
class ProfileViewUpdate(generics.UpdateAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
lookup_field = 'token'
lookup_url_kwarg = 'pk'
序列化器:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('token','bio','name','email','sport','location','image')
console.log(this.state.file.file.name) filestate
我也尝试使用JSON数据进行更新,但效果不佳:
handleFormSubmit = (event) => {
const name = event.target.elements.name.value;
const email = event.target.elements.email.value;
const location = event.target.elements.name.value;
const sport = this.state.sport;
const image = this.state.file.file;
axios.defaults.headers = {
"Content-Type": "application/json",Authorization: this.props.token
}
const profileID = this.props.token
axios.patch(`http://127.0.0.1:8000/api/profile/${profileID}/update`,{
name: name,email: email,location: location,sport: sport,image: image,})
.then(res => console.log(res))
.catch(error => console.err(error));
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)