(this is my first stackoverflow question ever)
I want to return JsonResponse from the dictionary "context" (seems to be a paginator Page) as coded below:
myposts = userposts.all().values()
myfollowers = userfollowers.ffollowers.all()
myfollowings = userfollowers.ffollowings.all()
context = {"posts": page_obj,
"loops": range(1, totalpages + 1),
"user": uprofile.username,
"myposts": list(myposts),
"mypostsnum": len(userposts.all()),
"myfollowers": list(myfollowers),
"myfollowersnum": len(userfollowers.ffollowers.all()),
"myfollowings": list(myfollowings),
"myfollowingsnum": len(userfollowers.ffollowings.all())
}
this is the return I use:
return JsonResponse(context, safe=False)
Result I get:
Object of type Page is not JSON serializable
My question is how do I get JsonResponse from 'context'?
The problem is with
"posts": page_obj
.page_obj
is an instance of a model. Likepage_obj = Post.objects.get(pk=1)
.JsonResponse
will calljson.dumps()
on your context and is failing because it doesn't know how to handle a object.I would recommend you to use Django rest framework for this. Serializers is used just for this problem.