繁体   English   中英

为什么 Django 没有检测到我在 javascript fetch POST 请求中发送的数据?

[英]Why isn't Django detecting the data I'm sending in a javascript fetch POST request?

我正在使用 fetch api 发布数据。 在正文中,我发送了employee_id,但我收到了来自 Django 的 MulitDictKey 错误,说它(以及其他数据,就此而言)没有收到。 为什么不发送? 有什么我想念的吗?

在我的 html 文件中(在脚本标签中):

const graduateEmployee = row => {
        const token = row.querySelector('INPUT').value
        fetch('/questions/ajax/update_employee', {
                method: 'POST',
                headers: {
                  "X-CSRFToken": token,
                  "Accept": "application/json",
                  'Content-Type': 'application/json'
                },
                body:JSON.stringify({
                    employee_id: row.id,
                    column: 'mentor_status',
                    new_value: false
                })
            }).then((res) => res.json())
            .then((response) =>  console.log('Success:', JSON.stringify(response)))
            .catch((err)=>console.log('Error:', err))
    }

在我的 views.py 中:

def update_employee(request):
    employee_id= int(request.POST["employee_id"])
    column = request.POST["column"]
    new_value = request.POST["new_value"]
    employee = Employee.objects.get(employee_id = employee_id)
    employee[column] = new_value
    employee.save()
    return HttpResponse(f'{column} column for employee with id{employee_id} set to {new_value}')

错误页面:

MultiValueDictKeyError at /questions/ajax/update_employee
'employee_id'
Request Method: GET
Request URL:    http://127.0.0.1:8001/questions/ajax/update_employee
Django Version: 2.2.2
Exception Type: MultiValueDictKeyError
Exception Value:    
'employee_id'
Exception Location: C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80
Python Executable:  C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.1
Python Path:    
['C:\\Users\\dklaver\\mentor-program\\mentor',
 'C:\\Users\\dklaver\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\dklaver\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\dklaver\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\dklaver\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\dklaver\\AppData\\Roaming\\Python\\Python37\\site-packages',
 'C:\\Users\\dklaver\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages',
 'C:\\Users\\dklaver\\mentor-program\\mentor\\helpers',
 'C:\\Users\\dklaver\\mentor-program\\mentor\\cron']
Server time:    Fri, 5 Jul 2019 17:42:18 +0000
Traceback Switch to copy-and-paste view
C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__
            list_ = super().__getitem__(key) …
▶ Local vars
During handling of the above exception ('employee_id'), another exception occurred:
C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py in inner
            response = get_response(request) …
▶ Local vars
C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py in _get_response
                response = self.process_exception_by_middleware(e, request) …
▶ Local vars
C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py in _wrapped_view
                return view_func(request, *args, **kwargs) …
▶ Local vars
C:\Users\dklaver\mentor-program\mentor\questions\views.py in update_employee
    employee_id= int(request.POST["employee_id"]) …
▶ Local vars
C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__
            raise MultiValueDictKeyError(key) …
▶ Local vars
Request information
GET
No GET data

POST
No POST data

FILES
No FILES data
#Remember to put 'X-Requested-With':'XMLHttpRequest' to headers
const data = JSON.stringify({
    'hello':'world',
})

fetch('{% url "/questions/ajax/update_employee" %}', {
        method:'POST',
        headers:{
            'Content-Type':'application/json', 
            'X-CSRFToken':'{{csrf_token}}',
            'X-Requested-With':'XMLHttpRequest'
        },
        body:data,
        mode:'cors',
        cache:'default',
        credentials:'include'      
    }).then((response)=>{
        console.log('well');        
    })


def apiValues(self, request):
    data = json.loads(request.body)
    print(data.hello)
    return JsonResponse({'ok':True}, status=200)

#Result will be 'World'

如果你想使用 request.POST 那么你需要发送一个 formData 而不是一个 json。

Mozilla 如何使用 FormData

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("csrfmiddlewaretoken", "{{ csrf_token }");

fetch('{% url "/questions/ajax/update_employee" %}', {
        method:'post',
        body:formData ,
        mode:'cors',
        cache:'default',
        credentials:'include',            
    }).then((response)=>{
   console.log('well')
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM