1

I am trying to pass stringified json parameter and serialized form into Django view like this:

JS:

var selected_items = legalEntitiesVendorAgreements_selectize.items;  
var data = $form.serializeArray();  
for (var i = 0; i < selected_items.length; ++i)
{           
    data.push({'legal_entity_own_id' : selected_items[i]});
}

View:

def my_view (request):
list_data = json.loads(request.body)
for x in list_data:
    // Do smth with x['some_predefined_field']

Basically, I have two big questions here:

  1. How do I combine $m_form and json_str in the data parameter
  2. How does my Django view code change in the part of parsing the request parameter. Specifically, will json.loads(request.body) and the for cycle still be working, and will Django syntax my_form = MyForm(request.POST) still be valid

And don't know even when to start from. I've examined this, but I've got a bad feeling that $m_form + json_str is not the right way here. Help me please!

Community
  • 1
  • 1
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

2 Answers2

1

You're trying to mix and match form data and JSON here. You need to choose one, and convert the other into that format.

For example, you could add your form data into the obj before serializing:

form_data = $m_form.serializeArray();
json_obj["form_data"] = form_data;
json_str = JSON.stringify(json_obj);

and now your Django view can access the deserialized form data via list_data["form_data"].

Or, you could post your form in the standard way, with the JSON as a value inside that form:

form_data = $m_form.serialize();
form_data["json_data"] = json_obj;
$.post(url, form_data);

Now your Django view will get a standard POST dictionary, and you can access most of its elements as normal but specificially deserialize the json_data element.

form = MyForm(request.POST)
json_data = json.loads(request.POST["json_data"])

(the form should just ignore the additional field).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

At last I got it working. Would like to share my solution:

jquery:

json_obj = [];

for (var i = 0; i < selected_items.length; ++i)
{           
    json_obj.push({'legal_entity_own_id' : selected_items[i]});
}

var data = $form.serialize() + '&json_data=' + JSON.stringify(json_obj);
$.post ('/create_vendor_agreement/' + vendor_id + '/', data);

View:

my_django_form = MyDjangoForm(request.POST) # As usual
list_data = json.loads(request.POST['json_data'])
for x in list_data:
    do_something_with(x['legal_entity_own_id'])
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121