Reputation: 126
In ListAPIView, I try to overload the class for rendering HTML and JSON as below. For JSON rendering, it is expected to provide serializer.data for Response to render JSON output. For HTML rendering, it is expected to provide context_data in dict type and template name for Response to render HTML.
To reuse rest framework existing code, I try extract rest framework already serialized data and overload the Response data with serialized data and template name in one go. The result is HTML template not rendered as expected due to the provided data not in dict type.
class UserProfileList(generics.ListAPIView):
model = UserProfile
serializer_class = UserProfileSerializer
template_name = 'userProfile/list.html'
queryset = UserProfile.objects.all()
def list(self, request, *args, **kwargs):
response = super(generics.ListAPIView, self).list(request, *args, **kwargs)
return Response(response.data, template_name=self.template_name)
I wonder if extension of Response to construct the object with serializer, data in dict type, template as parameters so that we can reuse the library without explicitly identifying the request format. Any hints or suggestions.
class UserProfileList(generics.ListAPIView):
model = UserProfile
serializer_class = UserProfileSerializer
template_name = 'userProfile/list.html'
queryset = UserProfile.objects.all()
def list(self, request, *args, **kwargs):
return Response(self.get_serilaizer(), self.get_context_data(), template_name=self.template_name)
Upvotes: 1
Views: 2286
Reputation: 17208
In your first version have you tried printing out response.data
? Undoubtedly it's not a dict, but some kind of serialized representation. Maybe a JSON string. You'd need to deserialize it if you want to hand it back as template context.
You might need something like this, based on code in the ListModelMixin:
self.object_list = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(self.object_list, many=True)
return Response(serializer.data, template_name=self.template_name)
Upvotes: 1