使用用户名 = 电子邮件保存用户时出现 IntegrityError

Posted

技术标签:

【中文标题】使用用户名 = 电子邮件保存用户时出现 IntegrityError【英文标题】:IntegrityError when saving user with username=email 【发布时间】:2011-03-14 01:51:37 【问题描述】:

我已经修改了我的应用程序,所以当新用户注册时,它的用户名和电子邮件是相同的。但是当创建一个新用户时,我收到 IntegrityError : (1062, "Duplicate entry 'my@email.com' for key 'username'"),但用户仍然是正确创建的。 在其中创建新用户的函数 register_new('temp_data' 是来自 form.cleaned_data 的字典):

def register_new(request):
    data = request.session['temp_data']
    email = data['email']
    password1 = data['password1']
    userdata = 'email': email, 'password1': password1
    backend = request.session['backend']
    user = backend.register(request, userdata)

,这里是registration.backend注册函数,创建新用户:

def register(self, request, userdata):
    logging.debug("backend.register")
    logging.debug(userdata)
    username, email, password = userdata['email'], userdata['email'], userdata['password1']
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)         
    new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
    return new_user

追溯:

File "/home/rails/site-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/home/rails//registration/views.py" in register_new
  112.     user = backend.register(request, userdata)
File "/home/rails/registration/backends/default/__init__.py" in register
  21.                                                                     password, site)
File "/home/rails/site-packages/django/db/transaction.py" in _commit_on_success
  240.                 res = func(*args, **kw)
File "/home/rails/registration/models.py" in create_inactive_user
  73.         new_user = User.objects.create_user(username, email, password)
File "/home/rails/site-packages/django/contrib/auth/models.py" in create_user
  105.         user.save()
File "/home/rails/site-packages/django/db/models/base.py" in save
  410.         self.save_base(force_insert=force_insert, force_update=force_update)
File "/home/rails/site-packages/django/db/models/base.py" in save_base
  495.                     result = manager._insert(values, return_id=update_pk)
File "/home/rails/site-packages/django/db/models/manager.py" in _insert
  177.         return insert_query(self.model, values, **kwargs)
File "/home/rails/site-packages/django/db/models/query.py" in insert_query
  1087.     return query.execute_sql(return_id)
File "/home/rails/site-packages/django/db/models/sql/subqueries.py" in execute_sql
  320.         cursor = super(InsertQuery, self).execute_sql(None)
File "/home/rails/site-packages/django/db/models/sql/query.py" in execute_sql
  2369.         cursor.execute(sql, params)
File "/home/rails/site-packages/django/db/backends/util.py" in execute
  19.             return self.cursor.execute(sql, params)
File "/home/rails/site-packages/django/db/backends/mysql/base.py" in execute
  84.             return self.cursor.execute(query, args)
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py" in execute
  173.             self.errorhandler(self, exc, value)
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: IntegrityError at /register_new/
Exception Value: (1062, "Duplicate entry 'my@email.com' for key 'username'")

我搜索了解决方案并发现了许多不同的解决方案,包括删除/同步表、在不同位置捕获 IntegrityError、更改表列的解码字段(我尝试设置为 utf8_bin 但没有结果)。如何解决这个问题?

表结构:

http://i27.tinypic.com/dotmjs.pnghttp://i32.tinypic.com/1zq79tj.png

我在 django docs 找到了这张票: http://code.djangoproject.com/ticket/3083 但是应该同时创建2个模型。在我的情况下,我猜不会发生这样的事情:/

更新 型号:

class User(models.Model):
    username = models.CharField(_('Email'), max_length=30, unique=True, help_text=_("Required. 30 characters or fewer."))
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), blank=True)
    password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
    is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
    is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."))
    is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))
    last_login = models.DateTimeField(_('last login'), default=datetime.datetime.now)
    date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now)

【问题讨论】:

能展示一下表格结构吗? username 字段是唯一的,表中不能有 2 个完全相同的用户名。 但许多项目,包括 ie django-lfs 使用类似的方法(使用用户名=email,email=email 创建用户)并且它有效。同样早些时候它在我的项目中工作,但是在 700 次提交之后,我无法找到问题的根源:/ 【参考方案1】:

我会在注册后端的这个 init 文件中发现 MySQLdb 错误,因为它首先会导致问题:

导入 MySQL 数据库

(...)
    new_user = None
    try:    
        new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
    except MySQLdb.IntegrityError:
        pass

【讨论】:

你为什么会忽略这个错误。如果其真正的重复用户 ID 问题怎么办?

以上是关于使用用户名 = 电子邮件保存用户时出现 IntegrityError的主要内容,如果未能解决你的问题,请参考以下文章

保存电子邮件附件时出现运行时错误 '91

用户在 Flask 上注册后发送邮件时出现循环导入问题

当用户在设备上没有电子邮件帐户时,在 IOS 上共享文档时出现问题

请求 gmail-api 时出现 HttpError 429:超出用户速率限制

使用“每个电子邮件地址一个帐户”时出现 FirebaseAuthInvalidCredentialsException

在 Spring Security 中添加新用户时出现异常