Reputation: 1926
I have to populate a select field based on another select field's selection. The first select is the school and the second select should be the classes in that school. I use an ajax call and in my view I have following code but without results:
def get_classes_by_school_id(request):
school_id = request.POST.get('school_id', None)
data = {
'listClasses': Classes.objects.filter(school=school_id).values('id', 'title', 'abbr')
}
return JsonResponse({'data': list(data)})
console.log($.parseJSON(data)); returns
{data: ["listClasses"]}
data:["listClasses"]
0:"listClasses"
Upvotes: 0
Views: 99
Reputation: 1926
here the way I solved it finaly :
def get_classes_by_school_id(request):
school_id = request.POST.get('school_id', None)
school = get_object_or_404(School, pk=school_id)
queryset = Classes.objects.filter(school=school).values('id', 'abbr')
data = [{'id': item['id'], 'abbr': item['abbr']} for item in queryset]
return HttpResponse(json.dumps(data), content_type='application/json')
and in my javascript:
var options = '';
$.each(data, function (key, element) {
options += '<option value="' + element.id + '">' + element.abbr + '</option>';
});
I couldn't get your responses working, but thx anyway...
Upvotes: 1
Reputation: 1370
>>> x = list({"key1" : value1 , "key2" : value2 })
["key1" , "key2"]
Try this
def get_classes_by_school_id(request):
school_id = request.POST.get('school_id', None)
data = {
'data': Classes.objects.filter(school=school_id).values('id', 'title', 'abbr')
}
return JsonResponse(data)
And in javascript
var = JSON.parse(response)
var list = response["data"]
Upvotes: 1
Reputation: 25539
Your data
variable is a dict
, but you did list(data)
later on. list(data)
basically converts a dict into a list, only taking the keys. In your data
data structure, the only key is listClasses
, that's why you got [listClasses]
in the end.
An example:
>>> list({1:2, 3:4})
[1, 3]
You might need:
return JsonResponse({'data': list(data['listClasses'])})
Upvotes: 2