unnonusr
unnonusr

Reputation: 121

username saving as null in django custom model

when i am sending post request to register new user from postman, username saves as blank/dash . why username saving as blank i dont get it. but when i add from django admin it saves correctly.

here is postman image postman post request image

and here is the result

django result after sending post request

Custom Account Manager

class CustomAccountManager(BaseUserManager):
    def create_superuser(self, email, username, password, **other_fields):
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_active', True)
        other_fields.setdefault('is_admin', True)
        other_fields.setdefault('is_superuser', True)
        if other_fields.get('is_staff') is not True:            
            raise ValueError(
                'Superuser must be assigned to is_staff=True.')
        if other_fields.get('is_superuser') is not True:
            raise ValueError(
                'Superuser must be assigned to is_superuser=True.')
        return self.create_user(email, username, password, **other_fields)

    def create_user(self, email, username, password, **other_fields):
        if not email:
            raise ValueError(_('You must provide an email address'))
        if not username:
            raise ValueError(_('You must provide an username'))
        if " " in username:
            raise ValueError(_('Username should not contain space'))
        email = self.normalize_email(email)
        user = self.model(email=email, username=username, **other_fields)
        user.set_password(password)
        user.save()
        return user 
   

Custom User Model


class NewUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True, null=False, blank=False)
    username = models.CharField(max_length=150, unique=True, null=True)
    first_name = models.CharField(max_length=150, blank=True)
    objects = CustomAccountManager()
    # more
    class Meta:
        verbose_name = 'NewUser'

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

    def __str__(self):
        return str(self.username)

model serializer

class RegisterNewUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = NewUser
        fields = ('email', 'password', 'username')
        extra_kwargs={'password':{'write_only':True}}
    def validate(self, data):
        if hasattr(self, 'initial_data'):
            unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys())
            if unknown_keys:
                raise ValidationError("Got unknown fields: {}".format(unknown_keys))
        return data
    def validate_username(self, value):
        if " " in value:
            raise serializers.ValidationError("Username should not contain space")
  
    def save(self):
        newuser = NewUser(email = self.validated_data['email'],
        username = self.validated_data['username']
        )
        password = self.validated_data['password']

        newuser.set_password(password)
        newuser.save()
        return newuser

post request

class RegistrationView(APIView):
    permission_classes = [ AllowAny ]
    def post(self, request):
        reg_serializer = RegisterNewUserSerializer(data = request.data)
        print(request.data)
        print(reg_serializer)
        if reg_serializer.is_valid():
            print('lololololololololololo')
            reg_serializer.save()
            return Response(data=request.data,status=status.HTTP_201_CREATED)
        return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 2

Views: 501

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

You validator should return the data, so:

def validate_username(self, value):
    if " " in value:
        raise serializers.ValidationError("Username should not contain space")
    #        ↓ return the value
    return value

In Python a function call always returns something (unless an exception is raised). If no explicit return statement is triggered, None is returned.

Upvotes: 2

Related Questions