使用Django REST Framework渲染模板

时间:2017-11-03 03:50:52

标签: python django django-rest-framework

现在,我正在用他的网站帮助朋友用Django REST Framework构建。我并不是很熟悉它,所以当我打开包含视图的模块时,我感到困惑的是我需要为视图加载模板:

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)

我以前做return render(request, 'some_template.html', context) 我知道序列化基本上是什么,但我不知道如何使用它来加载模板或者我应该这样做。遗憾

1 个答案:

答案 0 :(得分:1)

根据其他框架文档,试试这个

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')

如果您想了解更多信息,请参阅API docs