Django Rest Framework自定义返回响应 [英] Django rest framework custom return response

查看:114
本文介绍了Django Rest Framework自定义返回响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个用于注册用户的自定义注册API,但是当用户成功注册时,我希望它显示以下消息:您已成功注册帐户!"但是我尝试了另一种方法,但是却收到错误消息.

So I have this custom register API which registers a user, but when user successfully register, I want it to have this message "You have successfully register an account!" But I tried a different method but get an error instead.

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

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

I tried changing this into the serializer

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

但是却出现错误.我不确定如何执行自定义响应,因为我只知道它是在 views.py 上完成的.但是,如果我是这样看的:

But got an error instead. I'm unsure how to do the custom response as I only know it is to be done on views.py. But if I do this on view:

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经验.

It will show this even if the validation is incorrect. Please help me as I'm still inexperienced in DRF.

推荐答案

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)

这篇关于Django Rest Framework自定义返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆