开发者

Avoiding Django's QueryDict List limitations

I'm trying to send data from a webpage to a django view to be saved as serialized json to a database. If possible, I would like to avoid django's QueryDict object and just read the request with simplejson, flatten, and save to the database. What is the best way to send the data so simplejson can flatten it?

var languages = {};
languages['english'] = ['mark', 'james'];
languages['spanish'] = ['amy', 'john'];

$.ajax({
    type: 'POST',
    url: '/save/',
    data: languages,
    dataType: 'json'
});

.

if开发者_JAVA技巧 request.is_ajax() and request.method == 'POST':
    for key in request.POST:
        print key
        valuelist = request.POST.getlist(key)
        print valuelist


I doubt that it is possible to make django avoid creating QueryDict, but you can ignore it (from iphone Json POST request to Django server creates QueryDict within QueryDict):

def view_example(request):
    data=simplejson.loads(request.raw_post_data)


Have you tried the QueryDict.lists() or QueryDict.dict() methods? https://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects


You can try http://code.google.com/p/jquery-json/ and make json string on client side.

var languages = {};
languages['english'] = ['mark', 'james'];
languages['spanish'] = ['amy', 'john'];

var json_languages = $.toJSON(languages);//'{"plugin":"jquery-json","version":2.2}'

// '{"spanish": ["amy", "john"], "english": ["mark", "james"]}'

$.post('/save/', {data: json_languages});

in view just:

if request.is_ajax() and request.method == 'POST':
     data = request.POST.get('languages')

it's not the best practice, but it works fine for me sometimes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜