我在Django请求中哪里找到我的JSON数据?

206 投票
13 回答
271616 浏览
提问于 2025-04-15 13:17

我正在尝试用Django/Python处理进来的JSON/Ajax请求。

request.is_ajax()在请求中返回True,但我不知道JSON数据的内容在哪里。

request.POST.dir包含以下内容:

['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
 '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding', 
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding', 
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 
'urlencode', 'values']

看起来请求的POST键中没有任何键。

当我在Firebug中查看POST请求时,发现确实有JSON数据被发送。

13 个回答

47

方法 1

客户端:以 JSON 格式发送

$.ajax({
    url: 'example.com/ajax/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    processData: false,
    data: JSON.stringify({'name':'John', 'age': 42}),
    ...
});

//Sent as a JSON object {'name':'John', 'age': 42}

服务器:

data = json.loads(request.body) # {'name':'John', 'age': 42}

方法 2

客户端:以 x-www-form-urlencoded 格式发送
(注意:contentTypeprocessData 已经改变,不需要使用 JSON.stringify

$.ajax({
    url: 'example.com/ajax/',
    type: 'POST',    
    data: {'name':'John', 'age': 42},
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',  //Default
    processData: true,       
});

//Sent as a query string name=John&age=42

服务器:

data = request.POST # will be <QueryDict: {u'name':u'John', u'age': 42}>

在 1.5 版本及以上的变化:https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests

HTTP 请求中的非表单数据 :
request.POST 将不再包含通过 HTTP 请求发送的非表单特定内容类型的数据。在之前的版本中,使用 multipart/form-data 或 application/x-www-form-urlencoded 以外的内容类型发送的数据仍然会出现在 request.POST 属性中。开发者如果想要访问这些情况下的原始 POST 数据,应该使用 request.body 属性。

可能相关的内容

91

我也遇到过同样的问题。我之前发送了一个复杂的JSON响应,但我无法通过request.POST这个字典来读取我的数据。

我的JSON POST数据是:

//JavaScript code:
//Requires json2.js and jQuery.
var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
json_response = JSON.stringify(response); // proper serialization method, read 
                                          // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
$.post('url',json_response);

在这种情况下,你需要使用aurealus提供的方法。读取request.body,然后用json标准库来反序列化它。

#Django code:
import json
def save_data(request):
  if request.method == 'POST':
    json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4
    try:
      data = json_data['data']
    except KeyError:
      HttpResponseServerError("Malformed data!")
    HttpResponse("Got json data")
267

如果你要把JSON数据发送到Django,建议你使用 request.body(在Django 1.4之前用 request.raw_post_data)。这样你就能得到通过POST请求发送的原始JSON数据。接下来你可以对这些数据进行进一步处理。

下面是一个使用JavaScript、jQuery、jquery-json和Django的例子。

JavaScript代码:

var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
               allDay: calEvent.allDay };
$.ajax({
    url: '/event/save-json/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: $.toJSON(myEvent),
    dataType: 'text',
    success: function(result) {
        alert(result.Result);
    }
});

Django代码:

def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.body   
    return HttpResponse("OK")

Django 1.4之前的代码:

  def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.raw_post_data
    return HttpResponse("OK")

撰写回答