Friday, January 28, 2011

Re: request.POST parsing without form

Excerpts from taso's message of Fri Jan 28 17:05:21 -0200 2011:
> Hi,

Hi,

> I am using django strictly as a backend for data processing. As such I
> am not using any forms or templates, just database tables as models.
> The page is js driven and POSTing data is causing me some issues.
>
> A user action triggers a POST that looks like:
>
> action "update"
> data { "field1": 8,"id": 2 }
> (copied from firebug)

So, it's a POST with an "action" fiend and a "data" field that looks like
a JSON value, right?

> When I try to parse the POST data I get errors on every type of method
> I have tried. What I eventually would like to do is something like:
>
> if request.POST.__getitem__('xaction') == 'update':
> mydata = request.POST.__getitem__('data')
> model_to_update = modelname.get(id=mydata['id']
> for k,v in mydata:
> setattr(model_to_update, k, v)
> model_to_update.save()
>
> However every time I try to parse the "data" POST values I get errors.
> I wonder if I am missing some assumptions by not importing/using
> forms, or if there is a standard method to iterate through the POST
> data that I am missing. I have literally tried every \*get\* dict
> method from the docs and all throw errors (.list() throws numeric
> indicies errors, iteritems() throws not iterable, etc.)
>
> Any thoughts?

Did you tried un-encoding the JSON, like this:

from django.utils.simplejson import simplejson

data = simplejson.loads(request.POST['data'])
id = data['id']
...

> Thanks
> Taso

Regards,
Matías
--
Matías Aguirre <matiasaguirre@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment