Passing list of values to django view via jQuery ajax call
You can access this array by request.POST.getlist('terid[]') in the view
in javascript:
$.post(postUrl, {terid: values}, function(response){
alert(response);
});
in view.py:
request.POST.getlist('terid[]')
It works perfect for me.
I found a solution to my original problem. Posting it here as an answer, hopefully it helps somebody.
jQuery:
var postUrl = "http://localhost:8000/ingredients/";
$('li').click(function(){
values = [1, 2];
var jsonText = JSON.stringify(values);
$.ajax({
url: postUrl,
type: 'POST',
data: jsonText,
traditional: true,
dataType: 'html',
success: function(result){
$('#ingredients').append(result);
}
});
});
/ingredients/ view:
def ingredients(request):
if request.is_ajax():
ourid = json.loads(request.raw_post_data)
ingredients = Ingredience.objects.filter(food__id__in=ourid)
t = get_template('ingredients.html')
html = t.render(Context({'ingredients': ingredients,}))
return HttpResponse(html)
else:
html = '<p>This is not ajax</p>'
return HttpResponse(html)
This part is your problem:
ourid = request.POST.get('terid', False)
ingredients = Ingredience.objects.filter(food__id__in=ourid)
You need to deserialize the JSON string.
import json
ourid = json.loads(request.POST.get('terid'))