我正在为非营利组织开发 Django 网站。我在个人资料图片部分。我正在尝试使用图像作为提交按钮来上传图像。我有打开的文件选择器。然后,选择文件后提交。它应该保存上传到 Django 数据库的图像。到目前为止,我对 Django 视图的 AJAX 请求,其成功功能工作正常。但是,当我尝试将测试打印到终端时,Python 终端中没有打印任何内容。此外,图像没有适当更新。
# source\templates\profile-pages\child-profile.html
...
<script>
$(document).ready(function () {
if (typeof jQuery == 'undefined') {
console.error('jQuery is not loaded!');
} else {
console.log('jquery is loaded');
}
// Get the image and input elements
var imageButton = document.getElementById("image-button");
var fileInput = document.getElementById("file-input");
// Add a click event listener to the image element
imageButton.addEventListener("click", function (e) {
// Simulate a click on the hidden input element
e.preventDefault();
fileInput.click();
});
// Add a change event listener to the input element
fileInput.addEventListener("change", function (e) {
e.preventDefault();
// Get the selected file from the input element
var file = fileInput.files[0];
console.log(file);
console.log(typeof file);
// Create a URL for the file object
if (
!(
file.type == "image/jpeg" ||
file.type == "image/jpg" ||
file.type == "image/png"
)
){
alert("Image must be jpeg, jpg or png");
$("#fileInput").val("");
return False;
}
var formData = new FormData();
formData.append("newPic", file);
// Update the image source with the file URL
// imageButton.src = url;
$('#submitBtn').submit(submitF(e, formData));
});
function submitF(e, pic) {
e.preventDefault();
// if (!$("#fileInput").val()) {
// alert("Please choose a file");
// }
// var formData = new FormData(this);
console.log("form data. #picform submitted");
$.ajax({
headers: {
'X-CSRFToken': $("input[name=csrfmiddlewaretoken]").val(),
},
url: "{% url 'users:profile' %}",
// url: "/profile",
data: {
newPic: pic,
csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
},
method: "POST",
contentType: false, // Set contentType and processData to false for file uploads
processData: false,
success: function (data) {
alert("success ");
},
error: function (xhr, status, error) {
console.log("AJAX error: ", status, error);
},
});
// $("#imageButton").attr("src", formData);
}
});
</script>
...
{% load crispy_forms_tags %}
<div id="profile-row" class="row g-3">
<div id="profile-img-container" class="col-md-5">
<form id="picForm" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input
id="file-input"
type="file"
name="picture"
accept="image/*"
style="display: none"
/>
{% if request.user.profile_pic.url %}
<img
id="image-button"
src="{{ request.user.profile_pic.url }}"
style="
width: 100px;
height: 100px;
border: 1px solid black;
cursor: pointer;
"
/>
{% elif request.user.profile_pic.url == None %}
<img src="{% static '/profile-images/default.png' %}" />
<p>Test</p>
{% endif %}
<button type="submit" id="submitBtn" value="Submit">Submit</button>
</form>
</div>
...
# users\views.py
...
@login_required
def profile(request):
user = get_object_or_404(afbUsers)
if request.method == 'POST':
new_pic_file = request.FILES.get('newPic')
if new_pic_file:
print('testing 123', new_pic_file.name)
# Update the logic based on your model and how you want to handle the file
user.profile_pic = new_pic_file
user.save()
messages.success(request, 'Profile image update success!')
return JsonResponse({'status': 'success'})
else:
messages.error(request, 'No file uploaded.')
return JsonResponse({'status': 'error', 'message': 'No file uploaded.'})
context = {'user': user}
return render(request, 'profile-pages/child-profile.html', context)
...
您确定通过此查询获得正确的对象吗:
user = get_object_or_404(afbUsers)
您没有传递任何身份证件或任何东西。该请求可能有效,但您的代码无论如何都会在此处引发 404,并且它会向 AJAX 代码返回 404。