0

i am creating custom user model in django using abstract base user class, i want to create user with only two fields "phone and password " and name being the optional field , which i have set in my models .py that blank =true. i have created a rest api for user registration using my custom user model, but every time i try to create new user with phone and password it gives me below error:-

IntegrityError at /api/users/
UNIQUE constraint failed: accounts_user.name
Request Method: POST
Request URL:    http://127.0.0.1:8000/api/users/
Django Version: 3.0.1
Exception Type: IntegrityError
Exception Value:    
UNIQUE constraint failed: accounts_user.name
Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 396
Python Executable:  /usr/local/opt/python/bin/python3.7
Python Version: 3.7.6
Python Path:    
['/Users/raghav/milkbasketdemo/milkbasketdemo',
 '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
 '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
 '/usr/local/lib/python3.7/site-packages']

Please help where i am going wrong , i have searched and tried changing code number of times but nothing is working for me.

please find the below code of models.py

 class UserManager(BaseUserManager):

 def create_user(self,phone, password=None,is_staff=False,is_admin=False,is_active=True):

    if phone is None:
        raise TypeError('Users must have a phonenumber.')



    user = self.model(phone=phone)
    user.set_password(password)
    user.staff=is_staff
    user.admin=is_admin
    user.active=is_active
    user.save(using=self._db)

    return user

def create_staffuser(self, phone, password):
    """
    Creates and saves a staff user with the given email and password.
    """
    user = self.create_user(
        phone,
        password=password,
        is_staff=True
    )
#    user.staff = True
    user.save(using=self._db)
    return users

def create_superuser(self, phone, password):
    """
    Creates and saves a superuser with the given email and password.
    """
    user = self.create_user(
        phone=phone,
        password=password,
        is_staff=True,
        is_admin=True
    )
    #user.staff = True
    #user.admin = True
    #user.active=True
    user.save(using=self._db)
    return user

class User(AbstractBaseUser,PermissionsMixin):
phone_regex=RegexValidator(regex = r'^[6-9]\d{9}$',message='please enter the correct phonenumber')

#name_regex=RegexValidator(regex=r'/^[A-Za-z]+$/',message='Please enter the correct name')
phone=models.CharField(validators=[phone_regex],max_length=15,unique=True)
name=models.CharField(max_length=15,unique=True,blank=True)
date_joined=models.DateTimeField(verbose_name='date joined',auto_now_add=True)
last_login=models.DateTimeField(verbose_name='last login',auto_now=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False)
first_login=models.BooleanField(default=False)

USERNAME_FIELD='phone'
REQUIRED_FIELDS = []


objects = UserManager()

def __str__(self):

    return self.phone


@property
def token(self):

    return self._generate_jwt_token()

def get_full_name(self):

    return self.name

def has_perm(self, perm, obj=None):

    return True

def has_module_perms(self, app_label):

    return True

Below is code of serializer.py

class RegistrationSerializer(serializers.ModelSerializer):



password = serializers.CharField(
    max_length=128,
    min_length=8,
    write_only=True
)


token = serializers.CharField(max_length=255, read_only=True)

class Meta:

    fields = ['phone', 'password']

def create(self, validated_data):

    return User.objects.create_user(**validated_data)
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user190549
  • 397
  • 1
  • 7
  • 15
  • Your views.py ?? – Biplove Lamichhane May 07 '20 at 11:30
  • Remove the `unique=True` constraint from name field in your model. You can't keep `blank=True` and `unique=True` together. Hope this will resolve you problem. – Jeet May 07 '20 at 11:40
  • Thank you @Jeet its working now , i have a doubt still , that when i am not including name in my user creation method why it is still giving name error ? – user190549 May 07 '20 at 12:22
  • It's not about the creation method. When you save the model instance, it checks for all constraints you applied and throws error if any constraint fails. – Jeet May 07 '20 at 14:07

0 Answers0