尝试在django中处理json时获取内部服务器错误 [英] Getting internal server error when trying to handle json in django

查看:345
本文介绍了尝试在django中处理json时获取内部服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试接收从我的jquery帖子调用发送的json对象,如下面的代码所示。当

I'm trying to receive a json object sent from my jquery post call as seen below in the code. I get the "POST OK" callback when the

simplejson.loads(request.POST) 

已注释。但是一旦我尝试做一些请求,我得到内部服务器错误500.任何想法或任何其他方式来处理json?

is commented. But as soon i'm trying do do something with the request I get Internal server error 500. Any ideas or any other ways to handle json?

views.py

@csrf_exempt
def post_post(request):
print 'post_post'
if request.method == 'POST':
    print 'POST'
    messageData = simplejson.load(request.POST)
    return HttpResponse(simplejson.dumps("POST OK!"))
else:   
    return HttpResponse(simplejson.dumps("POST NOT OK!"))

projectViewModel.js

projectViewModel.js

    var m = "Hello World";
        console.log(m);
        $.ajax({
        url: 'postNewPost/',
        type: 'POST',
        dataType: 'json',
        data: {client_response: JSON.stringify(m)},
         success: function(result) {
                    console.log(result);
                } 
        });


推荐答案

这是因为您尝试将字典传递给 loads()方法。 request.POST 是一个带params的字典。您可以使用 request.raw_post_data 获得原始内容。

It's because you are trying to pass a dictionary to loads() method. request.POST is a dictionary with params. You can get raw content using request.raw_post_data.

另外 simplejson 在Django中被弃用,如果你使用Python 2.6+,你应该只使用Python json package( import json

Also simplejson is deprecated in Django and if you are using Python 2.6+ you should just use Python json package (import json)

同样在你的js代码中,你通过json代码传递param client_response 。在这种情况下,您只需要将 request.POST ['client_response'] 只传递给 loads()方法。但是最好的方式是直接通过json。

Also in your js code you passing param client_response with json in it. In this case you will need to pass only request.POST['client_response'] to loads() method. But the better way will be to pass json directly.

  data: JSON.stringify(m)

这篇关于尝试在django中处理json时获取内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆