簡體   English   中英

Django自定義用戶 - 不使用用戶名 - 用戶名唯一約束失敗

[英]Django Custom User - Not using username - Username unique constraint failed

所以我按照文檔推薦的方法對AbstractBaseUser進行了子類化,創建了自己的用戶模型。 這里的目標是使用一個名為mob_phone的新字段作為注冊和登錄的標識字段。

對於第一個用戶來說,它很有魅力。 它將用戶名字段設置為空 - 空白。但是當我注冊第二個用戶時,我得到“UNIQUE約束失敗:user_account_customuser.username”。

我基本上想完全取消用戶名字段。 我怎樣才能做到這一點?

我嘗試了很多其他地方的建議,但無濟於事。 我基本上需要找到一種方法,使用戶名字段不唯一或完全刪除它。

干杯!

院長

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

堆棧跟蹤:

回溯(最近一次調用最后一次):文件“manage.py”,第22行,在execute_from_command_line(sys.argv)文件“/home/dean/.local/lib/python3.5/site-packages/django/core/management / init .py“,第363行,在execute_from_command_line utility.execute()文件”/home/dean/.local/lib/python3.5/site-packages/django/core/management/ init .py“,第355行,在執行self.fetch_command(子命令).run_from_argv(self.argv)文件“/home/dean/.local/lib/python3.5/site-packages/django/core/management/base.py”,第283行,in run_from_argv self.execute(* args,** cmd_options)文件“/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py”,第63行,在execute return super(Command,self).execute(* args,** options)文件“/home/dean/.local/lib/python3.5/site-packages/django/core/management/base.py”,第330行,執行output = self.handle(* args,** options)文件“/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser。 PY”, 第183行,句柄self.UserModel._default_manager.db_manager(數據庫).create_superuser(** user_data)文件“/home/dean/Development/UrbanFox/UrbanFox/user_account/models.py”,第43行,在create_superuser中密碼=密碼文件“/home/dean/Development/UrbanFox/UrbanFox/user_account/models.py”,第32行,在create_user user.save中(using = self._db)文件“/home/dean/.local/lib/python3.5 /site-packages/django/contrib/auth/base_user.py“,第80行,在save super(AbstractBaseUser,self).save(* args,** kwargs)文件”/home/dean/.local/lib/python3 .5 / site-packages / django / db / models / base.py“,第807行,保存force_update = force_update,update_fields = update_fields)文件”/home/dean/.local/lib/python3.5/site-packages /django/db/models/base.py“,第837行,在save_base中更新= self._save_table(raw,cls,force_insert,force_update,using,update_fields)文件”/home/dean/.local/lib/python3.5 /site-packages/django/db/models/base.py“,第923行,在_save_table結果= self._do_insert(cls._base_manager,using,fi elds,update_pk,raw)文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”,第962行,在_do_insert中使用= using,raw = raw)文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/manager.py”,第85行,在manager_method中返回getattr(self.get_queryset(),name)(* args ,** kwargs)文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/query.py”,第1076行,在_insert中返回query.get_compiler(using = using) .execute_sql(return_id)文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py”,第1107行,在execute_sql中的cursor.execute(sql,params) )文件“/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py”,第80行,執行返回super(CursorDebugWrapper,self).execute(sql,params) )文件“/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py”,第65行,在執行中返回self.cursor.execute(sql,params)文件“ /home/dean/.local/lib/python3.5/site-packages/django/db/utils.py“,lin e 94, 退出 six.reraise(dj_exc_type,dj_exc_value,traceback)文件“/home/dean/.local/lib/python3.5/site-packages/django/utils/six.py”,第685行,再加注value.with_traceback(tb)文件“/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py”,第65行,執行返回self.cursor.execute(sql) ,params)文件“/home/dean/.local/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py”,第328行,在執行返回Database.Cursor.execute(self, query,params)django.db.utils.IntegrityError:UNIQUE約束失敗:user_account_customuser.username

好吧,我是個白痴。 在發布此信息后幾秒鍾,我發現了一個明顯的解決方案:

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

只需覆蓋用戶名字段,使其不唯一。

橡皮鴨理論在行動....

可能是因為您已經在數據庫中輸入了一些必須與約束相矛盾的數據。 因此,請嘗試刪除該數據或整個數據庫,然后再次運行該命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM