Home > other >  how to store user details into database using serializers
how to store user details into database using serializers

Time:09-28

def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid():

       return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

CodePudding user response:

To store user details,

In serializers.py:

do this

class UserSerializer(serializers.ModelSerializer):
    '''Serializers for the user object.'''

    class Meta:
        model = model name here
        fields = ['email', 'password', 'name']
        extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}

    def create(self, validated_data):
        '''Create and return a user with encrypted password.'''
        return get_user_model().objects.create_user(**validated_data)

    def update(self, instance, validated_data):
        '''Update and return user.'''
        password = validated_data.pop('password', None)
        user = super().update(instance, validated_data)

        if password:
            user.set_password(password)
            user.save()

        return user

This is the way you can store user details in database

CodePudding user response:

just add this serializer.save() into your code :

def post(self, request): 
    serializer = UserSerializer(data=request.data) 
    if serializer.is_valid():
       serializer.save()

       return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • Related