I am trying to make a json array in django but I am getting error -
In order to allow non-dict objects to be serialized set the safe parameter to False
and my views.py -
def wall_copy(request):
if True:
posts = user_post.objects.order_by('id')[:20].reverse()
return JsonResponse(posts)
Basically user_post is a model a posts is the object of top 20 saved data. I want to send a json array but I am unable to convert posts into a json array. I also tried serializers but it didnt helped.
I am stuck help me please.
Thanks in advance.
Would this solve your problem?
from django.core import serializers
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
posts_serialized = serializers.serialize('json', posts)
return JsonResponse(posts_serialized, safe=False)
You can solve this by using safe=False
:
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
return JsonResponse(posts, safe=False)
Note that it's not really unsafe - you just have to make sure on your own, that what you are trying to return can be converted to JSON.
See JsonResponse docs for reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With