4

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 request.is_ajax() and request.method == 'POST':
    for key in request.POST:
        print key
        valuelist = request.POST.getlist(key)
        print valuelist
vii
  • 65
  • 1
  • 4

3 Answers3

5

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)

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194
4

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

Johntron
  • 2,443
  • 2
  • 24
  • 26
  • at the time of the question, the dict() method is available in the current development version and will be found in django 1.4+ ... – StefanNch Feb 12 '12 at 14:05
1

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.

Pill
  • 4,815
  • 1
  • 24
  • 26