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

因此,我按照文档建议通过对AbstractBaseUser进行子类化来创建自己的用户模型。这里的目标是使用一个名为mob_phone的新字段作为注册和登录的标识字段。

它对第一个用户有效。它将用户名字段设置为空-空白。但是当我注册第二个用户时,出现“唯一约束失败: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

堆栈跟踪:

追溯(最近一次通话):
在第22行的文件“ manage.py”中
execute_from_command_line(sys.argv)
在execute_from_command_line的第363行,文件“ /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行
返回super(Command,self).execute(* args,** options)
执行中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/core/management/base.py”,第330行
输出= self.handle(* args,** options)
句柄中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py”
self.UserModel._default_manager.db_manager(database).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(using = self._db)
保存文件“ /home/dean/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py”,第80行
超级(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中的第837行中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”
更新= self._save_table(原始,cls,force_insert,force_update,使用,update_fields)
_save_table中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”,第923行
结果= self._do_insert(cls._base_manager,使用字段,update_pk,原始
_do_insert中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/db/models/base.py”,行962
使用=使用,原始=原始)
在manager_method中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/db/models/manager.py”,第85行
返回getattr(self.get_queryset(),name)(* args,** kwargs)
_insert中的文件“ /home/dean/.local/lib/python3.5/site-packages/django/db/models/query.py”,行1076
返回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行
返回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”,第94行,位于出口
6.reraise(dj_exc_type,dj_exc_value,回溯)
重新列出文件“ /home/dean/.local/lib/python3.5/site-packages/django/utils/six.py”,行685
提高价值.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(自我,查询,参数)
django.db.utils.IntegrityError:唯一约束失败:user_account_customuser.username

参考方案

好吧,我是个白痴。从字面上看这发布后几秒钟,我想到了一个明显的解决方案:

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

只需覆盖用户名字段并使其非唯一即可。

橡皮鸭理论在行动。

Django:错误:您无权访问该端口 - python

我是整个安装的新手,请保持友善。在dev上,该命令通常可以正常工作,但是自从我尝试使用Django的不同命令以来,某些东西就出错了。python manage.py runserver 0.0.0.0:80 我没有使用此端口的权限了。我可以使用端口8080,但将端口添加到url中通常的主机名末尾时,网站无法正常工作。当我使用端口80时,无论如何我都无需在UR…

Django-一个CBV可处理多种情况 - python

我很难理解如何使用单个CBV处理(至少)2种不同情况。这是我想做的事情:我有一个ListView来显示对象列表。从那里,我生成一个链接以导航到DetailView以显示对象的详细信息。从那里,我生成一个链接到呈现相关报告的不同视图。我想使用以下网址:1. /myapp/list.html/ 2. /myapp/detail.html/<<uuid…

Django:DateField“此字段不能为空。” - python

我发布这样的休息请求:{title:some title, recurring:true, day:Wednesday, time:12:30, description:some text} 我没有传递日期,因为该事件重复发生,并且该值应该为空。服务器响应为:{"date": ["This field cannot be bla…

Django TestCase不保存我的模型 - python

我目前正在为Django应用编写一些测试。我的应用程序的signal.py文件中具有以下独立功能:def updateLeaveCounts(): # Setting some variables here todaysPeriods = Period.objects.filter(end__lte=today_end, end__gte=today_sta…

django-simple-history,在admin中显示更改的字段 - python

当我从admin.ModelAdmin继承时,在管理页面的历史记录中,我可以看到哪些字段已更改。但是,现在我需要使用django-simple-history来跟踪所有模型更改。现在,对于管理员,我继承了simple_history.SimpleHistoryAdmin。我可以看到所有模型更改并还原它们,但看不到更改了哪些字段。是否可以在SimpleHist…