在Django中执行save()函数时网页为何自动刷新?
问题原因及解决方案
导致页面刷新的核心原因
你的按钮类型是type="submit",尽管表单加了onsubmit="return false",且在upload方法里调用了event.preventDefault(),但异步函数的执行顺序导致默认提交行为没被彻底阻断:
event.preventDefault()在函数开头执行,但axios.post是异步操作,浏览器的表单默认提交行为可能在异步逻辑完成前就触发了。- 同时使用
await和.then()的混合写法属于冗余操作,也可能导致事件处理逻辑混乱。
修复步骤
- 修改按钮类型:把按钮的
type="submit"改成type="button",从根源上避免触发表单默认提交行为:
<button type="button" @click="upload">Upload</button>
- 简化axios逻辑:去掉冗余的
.then(),统一用await写法,让代码更清晰:
async upload(event) { const fileInput = this.$refs.fileInput; const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); try { const response = await axios.post(this.APIip + "/api/file/upload", formData, { headers: { 'Authorization': 'token ' + this.token } }); // 可在此添加上传成功后的逻辑,比如提示用户 } catch (error) { console.log(error); } }
- 移除冗余代码:表单的
onsubmit="return false"可以删掉,因为按钮已不是submit类型。
额外优化建议
- 不要手动设置
Content-Type: multipart/form-data,axios传入FormData时会自动设置正确的请求头,手动设置反而可能引发请求异常。 - Django视图需补全异常处理,避免无文件时出现变量未定义报错:
@csrf_exempt @api_view(['POST']) def upload_file(request): if request.method == "POST": file = request.FILES.get('file') if file: filename = file.name post = ModelWithFileField() post.upload = file post.OnlyForDatabase = file post.filename = filename post.upload_date = date.today() post.save() return Response(post.id, status=status.HTTP_201_CREATED) return Response("No file provided", status=status.HTTP_400_BAD_REQUEST)
内容的提问来源于stack exchange,提问作者Minse
相关产品推荐
相关产品推荐

