Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering templates with Django REST Framework

Right now I'm helping a friend out with his site that's built with Django REST Framework. I'm not really familiar with it so when I opened the module that contained the views I was confused as to where I need to load the template for the view:

class ProfileView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):
        serialized = UserProfileSer(instance=request.user)
        return Response(serialized.data)

    def post(self, request):
        serialized = UserProfileSer(instance=request.user, data=request.data, partial=True)
        if serialized.is_valid():
            serialized.save()
            return Response(serialized.data)

        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

I'm used to doing return render(request, 'some_template.html', context) I know what serializing does basically but I don't know how to use it to load a template or if I'm supposed to. Sorry

like image 734
Amon Avatar asked Sep 14 '25 02:09

Amon


1 Answers

as per the rest framework document, try this

class UserDetail(generics.RetrieveAPIView):
    """
    A view that returns a templated HTML representation of a given user.
    """
    queryset = User.objects.all()
    renderer_classes = (TemplateHTMLRenderer,)

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return Response({'user': self.object}, template_name='user_detail.html')

If you want know more the refer the API docs

like image 186
Robert Avatar answered Sep 15 '25 15:09

Robert