Django在基于通用类的视图中返回响应

时间:2018-07-30 11:17:49

标签: django django-rest-framework

我有一个基于通用类的视图,并且我试图根据某些条件返回响应,但是这种情况没有发生。

# Create your views here.
class UserViewCreate(generics.CreateAPIView):

    queryset = User.objects.all()
    serializer_class = UserSerializer
    response = HttpResponse('')

   def perform_create(self, serializer):
       if serializer.is_valid():
           if self.check_signin_details(self.request.data):
               serializer.save()
               self.response.status_code = 201
               self.response["message"] = "User created successfully."
               return self.response
           else:
               self.response.status_code = 400
               self.response["message"] = "Password or username policy failed."
               return self.response

    @staticmethod
    def check_signin_details(data):
        return len(data['username']) < 11 and len(data['userpassword']) > 10

我期望我正在设置的响应和status_code。但是即使在其他情况下,我每次都得到201。简而言之,我没有收到自定义资源库。

2 个答案:

答案 0 :(得分:3)

覆盖视图的create()方法,

from rest_framework.response import Response

class UserViewCreate(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if self.check_signin_details(self.request.data):
            self.perform_create(serializer)
            return Response(data={"message": "User created successfully."}, status=status.HTTP_201_CREATED)
        return Response(data={"message": "Password or username policy failed."}, status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    def check_signin_details(data):
        return len(data['username']) < 11 and len(data['userpassword']) < 10

我从您的视图中删除了perform_create()方法,这是无关紧要的,例如,只有通过自定义用户名/密码策略的情况下,它才会保存实例

答案 1 :(得分:2)

perform_create不返回http响应(请参阅source)。它只是保存对象。如果您需要修改响应,则应该覆盖create方法:

 def create(self, request, *args, **kwargs):
       serializer = self.get_serializer(data=request.data) 
       if serializer.is_valid():
           if self.check_signin_details(self.request.data):
               serializer.save()
               self.response.status_code = 201
               self.response["message"] = "User created successfully."
               return self.response
           else:
               self.response.status_code = 400
               self.response["message"] = "Password or username policy failed."
               return self.response