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

问题: I'm POSTing data using the fetch api. In the body I send the employee_id, yet I'm getting a MulitDictKey error from Django saying it (and the other data, for that matter) w...

问题:

I'm POSTing data using the fetch api. In the body I send the employee_id, yet I'm getting a MulitDictKey error from Django saying it (and the other data, for that matter) wasn't received. Why isn't it sending? Is there something I'm missing?

In my html file (in the script tag):

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

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

Error Page:

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:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangoutilsdatastructures.py in __getitem__, line 80
Python Executable:  C:UsersdklaverAppDataLocalProgramsPythonPython37-32python.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:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangoutilsdatastructures.py in __getitem__
            list_ = super().__getitem__(key) …
▶ Local vars
During handling of the above exception ('employee_id'), another exception occurred:
C:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocorehandlersexception.py in inner
            response = get_response(request) …
▶ Local vars
C:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocorehandlersbase.py in _get_response
                response = self.process_exception_by_middleware(e, request) …
▶ Local vars
C:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocorehandlersbase.py in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
C:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocontribauthdecorators.py in _wrapped_view
                return view_func(request, *args, **kwargs) …
▶ Local vars
C:Usersdklavermentor-programmentorquestionsviews.py in update_employee
    employee_id= int(request.POST["employee_id"]) …
▶ Local vars
C:UsersdklaverAppDataLocalProgramsPythonPython37-32libsite-packagesdjangoutilsdatastructures.py in __getitem__
            raise MultiValueDictKeyError(key) …
▶ Local vars
Request information
GET
No GET data

POST
No POST data

FILES
No FILES data

回答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'

if you want to use request.POST then you will need to send a formData instead of a 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')
})
  • 发表于 2019-07-07 23:15
  • 阅读 ( 915 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除