【问题标题】:Django - Error when changing from GET to POSTDjango - 从 GET 更改为 POST 时出错
【发布时间】:2022-01-20 18:39:34
【问题描述】:

我有一个 react/django 应用程序,当请求是 GET 请求时可以正常工作。例如,在 React 部分我有以下内容

sendRequestParameters(url) {
        axios({
            url: url,
            method: 'get',
            headers: {
                'X-CSRFToken': 'csrf_token',
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8',
            },
            params:{
                'TECHNOLOGY': JSON.stringify(this.state.technologySelectedValue),
                // more parameters here, all in the same format
            },
            paramsSerializer: function(params) {
                return qs.stringify(params, {arrayFormat: 'repeat'})
            }
        }).then((response ) => {  
           console.log(response.data);
        }).catch((error) => {
            console.log(error)
        }) 
    }

然后,在后端,我获取参数并返回它们(这个函数在另一个使用返回参数的函数中调用,这就是为什么有一个return语句)。

def extractParameters(request):
    TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY'))
    # more parameters extracted here, same format

    return TECHNOLOGY etc.

一切正常。但是,我需要更改为 POST 请求,并且当我进行两次小修改来执行此操作时,出现错误。在使用 axios 的前端请求中,我将method: 'get' 更改为method: 'post'。然后,在后端,我将TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) 更改为TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY'))

这给了我终端中的以下错误

TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY'))
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

我所做的只是从 GET 到 POST 的简单更改,它导致了这个错误。我一直在阅读 Django 文档,但被卡住了。任何帮助将不胜感激。

【问题讨论】:

    标签: python django post axios get


    【解决方案1】:

    我假设您使用的是 DRF(Django REST 框架)。你可以使用data获取它:

    TECHNOLOGY = request.data.get('TECHNOLOGY')
    

    也很抱歉,但从不使用大写请求参数和变量。

    【讨论】:

    • 感谢您的回答。我尝试了这个和许多其他的东西,但它不起作用。有一些更深层次的问题正在发生 - 这是我刚刚完成的时间表上的一个项目,我不得不将它们留在 GET,没什么大不了的。
    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    相关资源
    最近更新 更多