corycorycory corycorycory - 13 days ago 7
Javascript Question

Pass object to django view (controller) FROM template

I'm fairly new to django, but I'm a bit stumped on what the best practice is for what I would like to do.

In my web-app, when the user opens the page, django provides a JSON object through the context. The object contains a database of 100 objects.

The purpose of the page is to allow the user to select any number of objects from this list, and then when they click "SAVE", the users selections are saved in another database table.

Now, one option is to make it so that every time the person adds or removes an object, a django view is called, the object is added to the DB, and then user is returned to the page via

HttpResponseRedirect(request.META.get('HTTP_REFERER'))
.

I don't like this option because it requires not only writing to the database each time an option is selected, it also must reload and redirect the page each time. This seems inefficient.

So, what I would like to do is maintain the list in javascript, then feed a django view the ENTIRE list only once the user clicks "SAVE". I know this is possible by setting up a URL regex, but I'd rather not pass the data through the URL.

Any advice on the best practice for doing this?

EDIT:

Resolved! Serialized the list into a json object, then sent the object via an ajax post:

$.ajax({
type: "POST",
url:"/save/",
data: new_json,
success: function(){
alert('test')
},
error: function(){
alert("Error");
})

Answer

You can setup a URL and POST the data. No need to pass it via GET.