cosmos multi
cosmos multi

Reputation: 565

How is the correct way to send a json serializer

I am practicing with serializers and I find an error because I want to send json from my queryset and the error it generates is context must be a dict rather than JsonResponse, I read the documentation and it says that setting the safe parameter to false allows sending any object serializer:
This is my view:

class TypeTaskListView(ListView):
    template_name = 'tasks/type_task.html'
    queryset = TypeTask.objects.all().order_by('-pk')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        data = serializers.serialize('json', context['object_list'])

        return JsonResponse(data, safe=False)

Upvotes: 0

Views: 210

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can not return a JsonResponse out of a get_context_data, the code contract assumes that get_context_data returns a dictionary.

You will need to override the .render_to_response(…) method [Django-doc]:

from json import loads as jloads

class TypeTaskListView(ListView):
    template_name = 'tasks/type_task.html'
    queryset = TypeTask.objects.order_by('-pk')

    def render_to_response(self, context, **kwargs):
        data = serializers.serialize('json', context['object_list'])
        return JsonResponse({'data': jloads(data)})

That being said, it looks like you are constructing an API view, in that case you probably better work with the Django Rest Framework which has logic to implement API views, viewsets, serializers, permissions, etc.


Note: In 2008, Phil Haack discovered a way to obtain data from the outer JSON array. While most browser have implemented countermeasures, it is still better to use a JSON object as "envelope" of the data. That is why a JsonResponse [Django-doc] by default does not allow something else than a dict as outer object. It might thus better to use a dictionary and keep safe=True on True.

Upvotes: 1

Related Questions