我正在编写一个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})
型
1条答案
按热度按时间k5ifujac1#
工作脚本应为:
字符串