Django - TypeError on deserializing json from jQuery POST -
i'm pushing fair amount of data via jquery ajax django app in form of json. data received server, can't parse it.
in views file, have
from django.http import httpresponse django.utils import simplejson def savestrategy(request): if not request.user.is_authenticated: return httpresponse(simplejson.dumps({"response" : "failure"})) else: #this section here throws typeerror - expected string or buffer #update_tasks = simplejson.loads(request.post.get("tasks", false)) #update_strategy = simplejson.loads(request.post.get("strategy", false)) update_strategy = request.post.get("strategy", false) update_tasks = request.post.get("tasks", false) print update_strategy return httpresponse(simplejson.dumps({"response" : "success"}))
which destination of
if (typeof currenttaskid !== "undefined") { $("#save_strategy_task").trigger("click"); localtasks = json.stringify(tasks) } else localtasks = {}; .ajax({ url : "savestrategy/", type : "post", data : {"strategy" : json.stringify(strategy), "tasks" : localtasks}, datatype : "json", success : function(data) { if (data.response == "success") strategydetailclosehandler(); } });
now, when update_strategy
not involved simplejson
, get
{ "title":"title", "status":"pending", "strategy":"strategy", "duedate":"", "owner":"", "metrics":"test", "id":"3", "outcome":"outcome1" }
however, if try
print update_strategy["id"]
i typeerror: string indices must integers
error.
how can parse incoming json update existing model object?
there number of issues in code relating expected types of variables. example, in javascript snippet, localtasks
may either javascript object {}
, or may string json.stringify(tasks)
.
when posted server, there call
update_tasks = simplejson.loads(request.post.get("tasks", false))
which has potential return boolean value false
if tasks
isn't present in response.
what believe happening this:
- on client,
localtasks = {}
. - when
.ajax
call occurs, doesn't know how handletasks
entry because.ajax
expects key/value pairs , doesn't send contents oftasks
server. - the
update_tasks = simplejson.loads(request.post.get("tasks", false))
code on server attemptstasks
tasks
isn't inrequest.post
false
returned. - the json parser attempts
loads(false)
, resulting in error.
to fix these issues:
- always have
localtasks
converted consistent type on client. ie ensure has been converted string. - don't
request.post.get('foo', false)
. instead,request.post.get('foo', '')
, handle error case when empty string returned.
Comments
Post a Comment