Modify response from Django REST API using CustomUserModel extending default User Model and API classes

天涯浪子 提交于 2019-12-02 06:46:25

If you override the default setting of the REST_AUTH_SERIALIZERS, you can apply a custom view for the response.

For example, in your settings.py file you must define REST_AUTH_SERIALIZERS dict.

#serializers.py
class MyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ('pk', 'username', 'email', 'first_name', 'last_name', 
                  'phone_no', 'user_android_id' )
        read_only_fields = ('email', )

#settings.py
"REST_AUTH_SERIALIZERS" : {
    "USER_DETAILS_SERIALIZER": MyUserSerializer
}

After alot of searching and applying various tests, I finally found the solution to my problem.

By using Custom model and Custom Serializer in Django User model, We could fully customize the views.py file where we apply our logic.

So below is the change I did in my views.py file:

from rest_framework.authtoken.models import Token
from app.serializers import MyUserSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

class CustomRegisterView(APIView):
    """
        User Registration API
    """
    def post(self, request):
        serializer = MyUserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            if user:
                token = Token.objects.create(user=user)
                # json = serializer.data
                # json['token'] = token.key
                response = {
                    'result': 1,
                    'key': token.key
                    'user_id': user.pk
                }
                return Response(response, status=status.HTTP_201_CREATED)

        # json = serializer.errors
        response = {
            'result':0,
            'msg':"User with email is already registered."
        }
        return Response(response, status=status.HTTP_400_BAD_REQUEST)

serializers.py file:

from app.models import User
from rest_framework import serializers

class MyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email', 'password', 'name', 'phone_no','created_at', 'user_android_id',
                  'user_fcm_token','user_social_flag', 'user_fb_id', 'user_android_app_version')

        def create(self, validated_data):
            user = User.objects.create_user(**validated_data)
            return user

**Improvements and suggestions are welcomed.

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