12👍
✅
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)
49👍
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.
3👍
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'))
- You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
- How to customize django rest auth password reset email content/template
- How to make follower-following system with django model
- {% load static %} and {% load staticfiles %}: which is preferred?
1👍
It seems you are setting the array to string here
data: {'terid': values},
It should be
data: {terid: values}
- Is the Global Request variable in Python/Django available?
- Django, Security and Settings
- Django docker – could not translate host name "db" to address: nodename nor servname provided, or not known
Source:stackexchange.com