Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass json and deserialize form in django

The issue is next: I send some post data with ajax to server. This data looks like:

data = {
  form : $(this).serialize(),
  some_array: [2,3,4,1]
}

How to get form object in django? request.POST['form'] returns a string with a form. I'm trying to use import json library.

But, when I run value = json.load(request.POST['some_array']) or form = json.load(request.POST['form']) it doesn't work.

Printing request.POST['form'] returns the following:

u'csrfmiddlewaretoken=I3LWAjfhZRGyd5NS3m9XcJkfklxNhxOR& address_city=%D0%9A%D0%B8%D1%97%D0%B2& address_street=2& address_building=3& delivery_time=2015-05-15'

like image 720
Andrew Avatar asked Feb 10 '23 07:02

Andrew


1 Answers

The form data is not encoded in JSON but as a query string. You can use urlparse.parse_qs from the standard library to parse that query string.

Example:

from urlparse import parse_qs


form_data = parse_qs(request.POST['form'].encode('ASCII'))  # Query strings use only ASCII code points so it is safe.

# To access address_city:
address_city = form_data['address_city'][0].decode('utf-8')

# If you plan to pass form_data to a Django Form,
# use QueryDict instead of parse_qs:
from django.http import QueryDict


form_data = QueryDict(request.POST['form'].encode('ASCII'))
like image 68
aumo Avatar answered Feb 13 '23 15:02

aumo