首页 > 解决方案 > Javascript formdata 对象不向 django 框架发送任何键、对值

问题描述

Django 框架无法从 XMLHttpRequest 打印发布数据,顺便说一下,我正在编写 vanilla javascript 而不是 jquery,请不要编写 jquery 答案。提前致谢。

下面是我的 HTML 代码

<form action="{% url 'feed:update_comment' comment.id %}" 
method="POST" onsubmit="UpdateComment(event)" 
class="comment-update-form">{% csrf_token %}

<div class="close-comment-box"onclick="this.parentElement.parentElement.classList.add('hide')">
<span>&times;</span>
</div>

<textarea name="body" id="post_body">{{comment.text}}</textarea>

<div class="btn-div">
<button type="submit" class="button">Update</button>
</div>
</form>

下面是我的香草 JAVASCRIPT

    function UpdateComment(event){
    event.preventDefault()
    let comment_field_to_update = event.target.parentElement.parentElement.parentElement.querySelector('.comment-text-div').querySelector('.feed_text_element')
    const data = new FormData(event.target);
    const xhttp = new XMLHttpRequest();
    xhttp.onload = (response)=>{
        console.log(response)
    }
    xhttp.open("POST",event.target.getAttribute("action","action"),true)
    xhttp.setRequestHeader("Content-Type",'application/x-www-formurlencoded')
    xhttp.setRequestHeader('X-CSRFToken',csrftoken)
    xhttp.send(data)
}

下面是我的 Python DJANGO 代码

    from django.http import JsonResponse
    @login_required
    def updateComment(request,id):
        if request.method == "POST":
        response = {}
        try:
            comment = Comment.objects.get(id=id)
            if comment.author == request.user:
                comment.text = request.POST['body']
                comment.save
                response['200'] = comment.text
                return JsonResponse(response)
            else:
                response['400'] = 'You Can"t Edit This Comment'
                return JsonResponse(response)
        except Comment.DoesNotExist:
            response['404'] = 'Comment Not Found'
            return JsonResponse(response)

以下是我从 DJANGO 得到的错误


    System check identified no issues (0 silenced).
    August 29, 2020 - 17:23:54
    Django version 2.2.14, using settings 'jumbo.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    Internal Server Error: /update_comment&comment_identifier=/9/
    Traceback (most recent call last):
    File "/usr/lib/python3/dist-packages/django/utils/datastructures.py", line 78, in __getitem__
    list_ = super().__getitem__(key)`enter code here`
    KeyError: 'body'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
       File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 34, in inner
         response = get_response(request)
       File "/usr/lib/python3/dist-packages/django/core/handlerenter code heres/base.py", line 115, 
       in _get_response
         response = self.process_exception_by_middleware(e, request)
       File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 113, in _get_response
         response = wrapped_callback(request, *callback_args, **callback_kwargs)
       File "/usr/lib/python3/dist-packages/django/contrib/auth/decorators.py", line 21, in 
         _wrapped_view
         return view_func(request, *args, **kwargs)
       File "/media/freduah/7A1809E218099E6F/Jumbo Media/jumbo/feed/views.py", line 235, in
          updateComment
          comment.text = request.POST['body']
       File "/usr/lib/python3/dist-packages/django/utils/datastructures.py", line 80, in __getitem__
          raise MultiValueDictKeyError(key)
          django.utils.datastructures.MultiValueDictKeyError: 'body'
          [29/Aug/2020 17:23:55] "POST /update_comment&comment_identifier=/9/ HTTP/1.1" 500 81293

当我切换到 jquery 时它工作正常,但我不想在我的代码中使用任何库。如果您可以请仅提供香草 javascript 解决方案的帮助

标签: javascriptdjango

解决方案


FormData将内容类型设置为multipart/form-data自动,而不是x-www-formurlencoded.

相应地删除setRequestHeader()并将其视为多部分服务器端


推荐阅读