django 使用JS更新个人资料照片

ws51t4hk  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(131)

我正在编写一个Django应用程序,其中有一个按钮可以更改个人资料照片,点击后,会出现一个文件选择屏幕。选择文件后,我看到上传成功消息,但我选择的新图像没有写入数据库。我好几天都过不了这一关。
模板js代码:

<script>
  // JavaScript
  document.addEventListener("DOMContentLoaded", function () {
    const uploadButton = document.getElementById("uploadButton");
    const fileInput = document.getElementById("fileInput");

    uploadButton.addEventListener("click", function () {
      fileInput.click(); 
    });

    fileInput.addEventListener("change", function () {
      const formData = new FormData(document.getElementById("profileForm"));

      fetch("{% url 'update_profil_photo' %}", {
        method: "POST",
        body: formData,
        headers: {
          "X-CSRFToken": '{{ csrf_token }}'
        }
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert("Sucessfully updated!");
        } else {
          alert("An error occured, please try again.");
        }
      })
      .catch(error => {
        alert("an error occured, please try again.");
      });
    });
  });
</script>

字符串
模板html:

<form method="post" enctype="multipart/form-data" action='{% url "update" %}' id="profileForm">
                          {% csrf_token %}
                          
                        <button class="btn btn-info" type="button" id="uploadButton">
                          <i class="fa fa-fw fa-camera"></i>
                          
                          <span>Change Photo</span>
                        </button><input id="fileInput" type="file" style="display: none;">
                      </div>
                    </div>


浏览次数:

@login_required
def update_profil_photo(request):
    user_profile = get_object_or_404(UserProfile, user=request.user)
    user = request.user
    if request.method == 'POST':
        profile_form = UserProfilePictureUpdateForm(request.POST, request.FILES, instance=user_profile)
        if profile_form.is_valid():
            profile_form.save()
            messages.success(request, 'Update is successful')
            return JsonResponse({'success': True})
                     
    else:
        profile_form = UserProfilePictureUpdateForm(instance=user_profile)
    return render(request, 'profile.html', {'profile_form': profile_form})

k5ifujac

k5ifujac1#

工作脚本应为:

document.addEventListener("DOMContentLoaded", function () {
  const uploadButton = document.getElementById("uploadButton");
  const fileInput = document.getElementById("fileInput");

  uploadButton.addEventListener("click", function () {
    fileInput.click(); // Trigger the file input element's click event
  });

  fileInput.addEventListener("change", function () {
    const formData = new FormData(); // Create a new FormData object
    formData.append("profile_photo", fileInput.files[0]); // Append the selected file to the form data

    const xhr = new XMLHttpRequest();

    // AJAX request
    xhr.onload = function () {
      if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        if (response.success) {
          alert("Success");
        } else {
          alert("Error");
        }
      } else {
        alert("Error");
      }
    };

    // AJAX request settings
    xhr.open("POST", "{% url 'update_profil_photo' %}", true);
    xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
    xhr.send(formData); // Send the form data as the request body
  });
});

字符串

相关问题