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

时间:2019-07-05 17:44:06

标签: javascript python django 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

1 个答案:

答案 0 :(得分:1)

#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。

How to use FormData by mozilla

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')
})