0

I am trying create user through an API, But i am struck on above error.

Below are the code of the User and its manager. Here, I am creating custom user model.

class UserManager(BaseUserManager):

    def create_user(self,username,email, password=None):

        if username is None:
            raise TypeError('Users should have a Username')
        if email is None:
            raise TypeError('Users should have a Email')

        user = self.model(username=username,email=self.normalize_email)
        user.set_password(password)
        user.save()
        return user


    def create_superuser(self,username,email, password=None):

        if password is None:
            raise TypeError('Password should not be none')
        
        user = self.create_user(username, email, password)
        user.save()
        return user

class User(AbstractBaseUser,PermissionsMixin):
    username = models.CharField(max_length=255, unique=True, db_index=True)
    email = models.EmailField(max_length=255,unique=True,db_index=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects= UserManager()

    def __str__(self):
        return self.email

Below is serializers.py file.

class RegisterSerializers(serializers.ModelSerializer):
    password = serializers.CharField(max_length=68, min_length=6, write_only=True)

    class Meta:
        model = User
        fields = ['email','username','password']

    def validate(self, attrs):
        email = attrs.get('email','')
        username = attrs.get('username','')

        if not username.isalnum():
            raise serializers.ValidationError('The username should only contain alphanumeric character')
        return attrs
        
    def create(self, validated_data):
        return User.objects.create_user(**validated_data)

Here is POST request in views.py

class RegisterView(generics.GenericAPIView):

    serializer_class = RegisterSerializers

    def post(self, request):
        user = request.data
        serializer = self.serializer_class(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        user_data = serializer.data

        return Response(user_data,status=status.HTTP_201_CREATED)

I am new to drf. Kindly help me out, thanks.

4

0 回答 0