Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Custom User - Not using username - Username unique constraint failed

Tags:

python

django

I created my own user model by sub-classing AbstractBaseUser as is recommended by the docs. The goal here was to use a new field called mob_phone as the identifying field for registration and log-in.

It works a charm - for the first user. It sets the username field as nothing - blank.But when I register a second user I get a "UNIQUE constraint failed: user_account_customuser.username".

I basically want to do away with the username field altogether. How can I achieve this?

I basically need to either find a way of making the username field not unique or remove it altogether.

models.py

from django.contrib.auth.models import AbstractUser, BaseUserManager


class MyUserManager(BaseUserManager):
    def create_user(self, mob_phone, email, password=None):
        """
        Creates and saves a User with the given mobile number and password.
        """
        if not mob_phone:
            raise ValueError('Users must mobile phone number')

        user = self.model(
            mob_phone=mob_phone,
            email=email
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, mob_phone, email, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            mob_phone=mob_phone,
            email=email,
            password=password
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractUser):
    mob_phone = models.CharField(blank=False, max_length=10, unique=True)
    is_admin = models.BooleanField(default=False)
    objects = MyUserManager()

    # override username field as indentifier field
    USERNAME_FIELD = 'mob_phone'
    EMAIL_FIELD = 'email'

    def get_full_name(self):
        return self.mob_phone

    def get_short_name(self):
        return self.mob_phone

    def __str__(self):              # __unicode__ on Python 2
        return self.mob_phone

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

Stacktrace:

Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/dean/.local/lib/python3.5/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/home/dean/.local/lib/python3.5/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dean/.local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/home/dean/.local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/dean/Development/UrbanFox/UrbanFox/user_account/models.py", line 43, in create_superuser password=password File "/home/dean/Development/UrbanFox/UrbanFox/user_account/models.py", line 32, in create_user user.save(using=self._db) File "/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/dean/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql cursor.execute(sql, params) File "/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/dean/.local/lib/python3.5/site-packages/django/db/utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/dean/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/dean/.local/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: user_account_customuser.username

like image 659
Dean Sherwin Avatar asked Jan 29 '23 19:01

Dean Sherwin


2 Answers

Okay I'm an idiot. Literally seconds after posting this the obvious solution occurred to me:

    username = models.CharField(max_length=40, unique=False, default='')

Just override the username field and make it non unique.

Rubber duck theory in action....

like image 83
Dean Sherwin Avatar answered Feb 02 '23 11:02

Dean Sherwin


It might be because you would have already entered some data in database which must be contradicting to the constraint. So try deleting that data or whole database and then run the command again.

like image 41
Yash Agrawal Avatar answered Feb 02 '23 11:02

Yash Agrawal