[英]I have two errors because of Django or Apache
When I try to send a POST request to http://localhost/upload-avatar/
I got two errors当我尝试向
http://localhost/upload-avatar/
发送 POST 请求时,出现了两个错误
Error 404 (Not Found)
未找到错误404)
SyntaxError: Unexpected token '<', "<.DOCTYPE "... is not valid JSON.
SyntaxError: 意外的标记 '<', "<.DOCTYPE "... 不是有效的 JSON。
I would like to understand what is the reason and how to fix this problem.我想了解是什么原因以及如何解决这个问题。 There are suspisions that the problem is in Apache. I am using wamp.
怀疑问题出在Apache,我用的是wamp。 I connected Django after some time of using and writing wamp code.
在使用和编写 wamp 代码一段时间后,我连接了 Django。 I configured Apache. I also checked the routing settings and the server startup, but the problem remains.
我配置了Apache,我也检查了路由设置和服务器启动,但问题依旧。 I ask for help in identifying and eliminating this problem.
我寻求帮助来识别和消除这个问题。 Thank you in advance!
先感谢您!
Code:代码:
JS:记者:
PhotoUpload.addEventListener('change', function() {
const file = this.files[0];
if (file) {
const reader = new FileReader();
reader.addEventListener('load', function() {
photo.setAttribute('src', this.result);
photo.classList.remove('alt-centered');
PhotoUpload.style.display = 'none';
const formData = new FormData();
formData.append('photo', file);
fetch('/upload-avatar/', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
});
reader.readAsDataURL(file);
} else {
photo.setAttribute('src', '#');
photo.classList.add('alt-centered');
PhotoUpload.style.display = 'block';
}
});
};
views.py视图.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.http import JsonResponse
@csrf_exempt
def upload_avatar(request):
if request.method == 'POST' and request.FILES.get('photo'):
photo = request.FILES['photo']
# Сохраните фотографию с помощью default_storage
filename = default_storage.save('photos/' + photo.name, photo)
return JsonResponse({'message': f'Photo uploaded successfully: {filename}'})
return JsonResponse({'error': 'An error occurred while uploading the photo.'})
urls.py网址.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from PhotoSave import views
urlpatterns = [
path('admin/', admin.site.urls),
path('upload-avatar/', views.upload_avatar, name='upload_avatar'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In the Apache file (httpd.conf) I only changed在 Apache 文件(httpd.conf)中我只改变了
<Directory "${SRVROOT}/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>
<Directory "${INSTALL_DIR}/www/Chat/MediaSave">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
and also added the line LoadModule wsgi_module modules/mod_wsgi.so
并且还添加了行
LoadModule wsgi_module modules/mod_wsgi.so
You are getting a Django error page from the view.您正在从视图中获得 Django 错误页面。 My advice is, catch the error and send the exception message to the client.
我的建议是,捕获错误并将异常消息发送给客户端。 In the case of a GET view I would advice you to call it by hand in the browser, but I understand it's difficult to call a POST view by hand (you should write a form that calls this view).
对于 GET 视图,我建议您在浏览器中手动调用它,但我知道手动调用 POST 视图很困难(您应该编写一个调用此视图的表单)。
@csrf_exempt
def upload_avatar(request):
if request.method == 'POST' and request.FILES.get('photo'):
try:
photo = request.FILES['photo']
# Сохраните фотографию с помощью default_storage
filename = default_storage.save('photos/' + photo.name, photo)
return JsonResponse({'message': f'Photo uploaded successfully: {filename}'})
except Exception as ex:
return JsonResponse({'exception': str(ex)})
return JsonResponse({'error': 'An error occurred while uploading the photo.'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.