Django Rest未成功执行AJAX

时间:2018-11-08 14:33:08

标签: jquery ajax django-rest-framework

我有一个Django REST APIView,它接受POST并修补对象:

class TicketDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    queryset = models.Ticket.objects.all()
    renderer_classes = [TemplateHTMLRenderer]
    template_name='ticket.html'


    def get_object(self, pk):
        try: 
            return models.Ticket.objects.get(pk=pk)
        except models.Ticket.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        ticket = self.get_object(pk)
        serializer = serializers.TicketSerializer(ticket)
        return Response({'ticket':ticket})  


    def put(self, request, pk, format=None):        
        ticket = self.get_object(pk)
        serializer = serializers.TicketSerializer(ticket, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(request.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def post(self, request, pk, format=None):       
        ticket = self.get_object(pk)
        serializer = serializers.TicketSerializer(ticket, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'Success':'Success'}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

通过jQuery AJAX提交调用POST方法:

		$('#change-status').submit(function(e) {
			e.preventDefault();
			var status = $('select[name="status"]').val();
			console.log('working');
			console.log(status);
			$.ajax({
		     dataType:'json',
			 type: "POST",
			 url: '/core/group/ticket/{{ ticket.id }}/',
			 data: {
				 'csrfmiddlewaretoken':'{{ csrf_token }}', 
				 'status':status,
				 },
			 success: function() {
				  alert('Yeah!');
			 }
			});
		});

POST请求有效且对象得到更新,但未调用AJAX成功函数。

我已经尝试从标准Response(request.data),Response(request.data,status = HTTP_200_OK)更改响应,如上面的代码所示。

我不明白为什么未触发成功功能。

任何人都有可能指引我正确方向的线索吗?

谢谢

1 个答案:

答案 0 :(得分:0)

知道了!

问题是我必须在APIView renderer_classes列表中包括JSONRenderer才能返回非HTML响应。

class TicketDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    queryset = models.Ticket.objects.all()
    renderer_classes = [TemplateHTMLRenderer, JSONRenderer]