Reputation: 613
And I want to pass two data queries result named mydata
and yourdata
, the problem is when I send only mydata
or yourdata
then its working fine but when I send in context variable its not working at all, I am new in django
so any kind of help would be appreciated thanks.
@csrf_exempt
def snippetrequests(request):
import json
mydata=changerequest.objects.filter(owner_id=request.user.id)
yourdata=changerequest.objects.filter(user_id=request.user.id)
mydata=serializers.serialize('json',mydata)
yourdata=serializers.serialize('json',yourdata)
if request.method == 'GET':
context = {
'mydata':mydata ,
'yourdata':yourdata
}
return HttpResponse(context, content_type="application/json" )
And I am getting Data from it using AJAX like this
$.ajax({
url: '/snippetrequests/',
type: 'GET',
data={},
success: function(data) {
// alert(data);
alert(data)
console.log(data)
var div1 = document.getElementById('snippet');
},
failure: function(data) {
alert('Got an error dude');
}
});
Upvotes: 0
Views: 179
Reputation: 1522
You can return context with the help of json.dumps(), like
return HttpResponse(json.dumps(context), content_type="application/json" )
json.dumps basically converts your context dictionary to a string.
If you see the HttpResponse class code it basically takes a string as content, content=b'' is taken as the default argument, where b meaning bytes, your content is then converted to bytestring and joined with b'' and set.
Hence you need to use json.dumps(content).
OR you can try JsonResponse which extends HttpResponse class, with default Content-Type header as application/json
from django.http import JsonResponse
return JsonResponse(context)
Upvotes: 0
Reputation: 11
You've serialized the model data, but not your direct response; it is still in dictionary format. As such, HTTPResponse
is likely just returning a string that kinda-sorta looks like JSON, instead of actual JSON.
Use json.dumps
as part of your return
statement.
return HttpResponse(json.dumps(context), content_type="application/json")
Or better yet, if you're using Django 1.7+, use the JsonResponse
object:
from django.http import JsonResponse
. . .
return JsonResponse(context)
Upvotes: 1