Django休息框架自定义返回响应

时间:2017-12-26 06:58:35

标签: django django-rest-framework response

所以我有这个注册用户的自定义注册API,但是当用户成功注册时,我希望它有这样的消息“你已经成功注册了一个帐户!”但我尝试了一种不同的方法,但却得到了错误。

serializer.py

class UserCreate2Serializer(ModelSerializer):
    email = EmailField(label='Email Address')
    valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
    birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False)

    class Meta:
        model = MyUser
        fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime']
        extra_kwargs = {"password": {"write_only": True}}

    def validate(self, data):  # to validate if the user have been used
        email = data['email']
        user_queryset = MyUser.objects.filter(email=email)
        if user_queryset.exists():
            raise ValidationError("This user has already registered.")
        return data

    def create(self, validated_data):
        username = validated_data['username']
        password = validated_data['password']
        email = validated_data['email']
        first_name = validated_data['first_name']
        last_name = validated_data['last_name']
        gender = validated_data['gender']
        nric = validated_data['nric']
        birthday = validated_data['birthday']
        birthTime = validated_data['birthTime']

        user_obj = MyUser(
            username = username,
            email = email,
            first_name = first_name,
            last_name = last_name,
            gender = gender,
            nric = nric,
            birthday = birthday,
            birthTime = birthTime,
        )

        user_obj.set_password(password)
        user_obj.save()
        return validated

views.py

class CreateUser2View(CreateAPIView):
    permission_classes = [AllowAny]
    serializer_class = UserCreate2Serializer
    queryset = MyUser.objects.all()

我尝试将其更改为序列化程序

user_obj.set_password(password)
user_obj.save()
content = {'Message': 'You have successfully register an account'}
return content

但是却得到了一个错误。我不确定如何进行自定义响应,因为我只知道要在views.py上完成。 但如果我在视图上这样做:

class CreateUser2View(CreateAPIView):
    permission_classes = [AllowAny]
    serializer_class = UserCreate2Serializer
    queryset = MyUser.objects.all()

    def post(self, request):
        content = {'Message': 'You have successfully register'}
        return Response(content, status=status.HTTP_200_OK)

即使验证不正确,也会显示此信息。请帮帮我,因为我对DRF缺乏经验。

1 个答案:

答案 0 :(得分:5)

class CreateUser2View(CreateAPIView):
    permission_classes = [AllowAny]
    serializer_class = UserCreate2Serializer
    queryset = MyUser.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({'Message': 'You have successfully register'}, status=status.HTTP_201_CREATED, headers=headers)