简体   繁体   English

由于 Django 或 Apache,我有两个错误

[英]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.

相关问题 由于路由器,我有两个不同的标头 - I have two different headers because of Router 不确定我是否有语法错误或代码错误 - Not sure whether I have syntax errors or errors with the code 我有两个冲突的循环 - I have two loops that are clashing 为什么会出现这两个错误? - Why am I getting these two errors? 我无缘无故在JSLint中遇到两个错误 - Two errors I get in JSLint for no good reason 当我单击 html 和 JavaScript 的联系表单按钮时出现问题 - I have issues when I click button for contact form of html and JavaScript which API of Django rest in heroku it gives this errors: HTTP ERROR 405 我有一个日期选择器,因为用户可能会向文本框写入无效字符,我想进行日期选择器验证 - I have one Datepicker and because of users may write invalid characters to textbox, i want to have datepicker validation 如何修复我遇到的 CSP 错误? - How do I fix the CSP errors I have? 我可以防止JavaScript中的愚蠢错误,因为该语言不需要分号吗? - Can I prevent stupid errors in JavaScript because the language does not require semicolons? Django 当我有 onclick 时按钮不提交 - Django button not submit when i have onclick
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM