Jin Nii Sama
Jin Nii Sama

Reputation: 747

Django rest framework custom return response

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.

Upvotes: 3

Views: 4878

Answers (2)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

from rest_framework import status
from rest_framework.views import exception_handler as base_handler


def exception_handler(exception, context):
    """
    Django rest framework for custom exception handler

    @exception  :  Exception
    @context    :  Context
    """
    response = base_handler(exception, context)

    if response is not None:
        response = custom_response(response)

    return response


def serializer_errors(data):
    """
    Django rest framework serializing the errors
    @data  : data is python error dictionary
    """
    errors = {}
    got_msg = False
    message = "Bad request."

    if isinstance(data, dict):
        for key, value in data.items():
            try:
                if isinstance(value, list):
                    value = ", ".join(value)
            except Exception:
                pass

            if not got_msg:
                if value:
                    message = value
                    got_msg = True
            errors[key] = value

    if not isinstance(message, str):
        message = "Bad request"
    return errors, message


def error(source, detail, code):
    """
    Create python dictionary of error
    @source : Where coming the error
    @detail : Error detail information
    """
    error = {}
    error["source"] = source
    error["detail"] = detail
    if code:
        error["code"] = code
    return error


def custom_response(response):
    """
    Modification the response of django rest framework

    @response : Return response
    """
    modified_data = {}
    modified_data["code"] = response.status_code
    modified_data["status"] = get_status(response.status_code)
    data, message = serializer_errors(response.data)
    modified_data["message"] = message
    modified_data["errors"] = data
    response.data = modified_data
    return response


def get_status(status_code):
    """
    Return result base on return http status

    @status_code : HTTP status code
    """
    result = ""

    if status_code == status.HTTP_200_OK:
        result = "Success"
    elif status_code == status.HTTP_201_CREATED:
        result = "Instance create"
    elif status_code == status.HTTP_204_NO_CONTENT:
        result = "Instance deleted"
    elif status_code == status.HTTP_403_FORBIDDEN:
        result = "Forbidden error"
    elif status_code == status.HTTP_404_NOT_FOUND:
        result = "Instance not found"
    elif status_code == status.HTTP_400_BAD_REQUEST:
        result = "Bad request"
    elif status_code == status.HTTP_401_UNAUTHORIZED:
        result = "Unauthorized request"
    elif status_code == status.HTTP_500_INTERNAL_SERVER_ERROR:
        result = "Internal server error"
    else:
        result = "Unknown error"

    return result

Upvotes: 0

Ykh
Ykh

Reputation: 7717

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)

Upvotes: 12

Related Questions