Django rest framework custom return response

五迷三道 提交于 2021-01-27 12:12:05

问题


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

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)

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


回答1:


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)


来源:https://stackoverflow.com/questions/47975001/django-rest-framework-custom-return-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!