Django自定义用户 - 不使用用户名 - 用户名唯一约束失败

时间:2017-08-10 16:40:58

标签: python django web

所以我按照文档推荐的方法对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行,in       execute_from_command_line(sys.argv中)     在execute_from_command_line中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/core/management/init.py”,第363行       utility.execute()     文件“/home/dean/.local/lib/python3.5/site-packages/django/core/management/init.py”,第355行,执行       self.fetch_command(子命令).run_from_argv(self.argv)     在run_from_argv中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/core/management/base.py”,第283行       self.execute(* args,** cmd_options)     文件“/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py”,第63行,执行       return super(命令,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)     在create_superuser中输入文件“/home/dean/Development/UrbanFox/UrbanFox/user_account/models.py”,第43行       密码=密码     在create_user中输入文件“/home/dean/Development/UrbanFox/UrbanFox/user_account/models.py”,第32行       user.save(使用= self._db)     文件“/home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py”,第80行,保存       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)     在save_base中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”,第837行       updated = self._save_table(raw,cls,force_insert,force_update,using,update_fields)     在_save_table中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”,第923行       result = self._do_insert(cls._base_manager,using,fields,update_pk,raw)     在_do_insert中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”,第962行       using = using,raw = raw)     在manager_method中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/manager.py”,第85行       return getattr(self.get_queryset(),name)(* args,** kwargs)     在_insert中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/query.py”,第1076行       return query.get_compiler(using = using).execute_sql(return_id)     在execute_sql中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py”,第1107行       cursor.execute(sql,params)     文件“/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py”,第80行,执行       return super(CursorDebugWrapper,self).execute(sql,params)     文件“/home/dean/.local/lib/python3.5/site-packages/django/db/backends/utils.py”,第65行,执行       return self.cursor.execute(sql,params)     在退出中输入文件“/home/dean/.local/lib/python3.5/site-packages/django/db/utils.py”,第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行,执行       return 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

2 个答案:

答案 0 :(得分:2)

好吧,我是个白痴。发布后几秒钟就出现了明显的解决方案:

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

只需覆盖用户名字段并使其不唯一。

橡皮鸭理论在行动......

答案 1 :(得分:1)

可能是因为您已经在数据库中输入了一些必须与约束相矛盾的数据。因此,请尝试删除该数据或整个数据库,然后再次运行该命令。