为什么我在Django中执行“保存”功能时网页会刷新?

6rqinv9w  于 2023-05-23  发布在  Go
关注(0)|答案(1)|浏览(118)

为什么我在Django中执行“保存”功能时网页会刷新?
这是我的Django、HTML和Vue代码。我不知道原因,但我知道在执行保存()函数后,网页会刷新。我不希望页面重置,因为这也会导致其他用户同时访问该网页刷新。数据上传成功,但是否有特定原因导致网页刷新?

@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)
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Performance Tuning Database</title>
</head>
<body>
  <div id="app">
    <form method="post" onsubmit="return false">
      <input type="file" ref="fileInput" />
      <button type="submit" @click="upload">Upload</button>
    </form>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script src="JS/welcome copy.js"></script>
</body>
</html>
new Vue({
  el: "#app",
  data: {
    APIip: sessionStorage.getItem('API_IP'),
    token: sessionStorage.getItem('token'),
  },
  methods: {
    async upload(event) {
      event.preventDefault(); 
      const fileInput = this.$refs.fileInput;
      const file = fileInput.files[0];
      const formData = new FormData();
      formData.append('file', file);
      console.log(formData)
      this.message = formData
      const response = await axios.post(this.APIip + "/api/file/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          'Authorization': 'token ' + this.token
        }
      })
      .then(response => {
        event.preventDefault(); 
      })
      .catch(error => {
        console.log(error);
      });
    }
  },
});
qxgroojn

qxgroojn1#

在Django中执行“保存()”函数后,网页会刷新,因为表单提交会触发刷新页面的默认行为。为了防止这种情况,您可以修改Vue代码,从表单标记中删除“onsubmit”属性,并使用Vue方法处理表单提交。
下面是更新的代码:

<form>
  <input type="file" ref="fileInput" />
  <button type="button" @click="upload">Upload</button>
</form>

在Vue方法中,删除event.preventDefault();行,因为它不再需要了。

async upload() {
  //event.preventDefault(); 
}

相关问题