Python Django类语法错误

时间:2019-07-09 10:56:29

标签: python python-3.x

我对python和django比较陌生。尝试实现python类但出现此奇怪的语法错误

from invoice.models import Invoice
from invoice.serializers import InvoiceSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class InvoiceList(APIView):

    def get(self, request, format=None):
        try:
            invoices = Invoice.objects.all()
            serializer = InvoiceSerializer(invoices, many=True)
            return Response(serializer.data)
        except Invoice.DoesNotExist:
            raise Http404
        serializer = InvoiceSerializer(invoices, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = InvoiceSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST


class InvoiceDetail(APIView):

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

    def get(self, request, pk, format=None):
        invoice=self.get_object(pk)
        serializer=InvoiceSerializer(invoice)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        invoice=self.get_object(pk)
        serializer=InvoiceSerializer(invoice, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        invoice=self.get_object(pk)
        invoice.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

这是我得到的错误。我不明白为什么会给我这个错误,因为我觉得错误

InvoiceDetail(APIView)类:         ^ SyntaxError:语法无效

1 个答案:

答案 0 :(得分:1)

在课程InvoiceList中进行更改

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)