使用用户名=电子邮件保存用户时出现完整性错误

发布于 2024-09-08 20:29:59 字数 5418 浏览 9 评论 0原文

我修改了我的应用程序,以便在注册新用户时,其用户名和电子邮件是相同的。但是,当创建新用户时,我收到 IntegrityError : (1062, "Duplicate Entry '[email protected]' 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

Traceback:

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 '[email protected]' for key 'username'")

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

表结构:

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

我在以下位置找到了这张票Django 文档: 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)

I have modified my application, so that when a new user is registered, it's username and email are the same. But when a new user is created, I'm getting IntegrityError : (1062, "Duplicate entry '[email protected]' for key 'username'"), still the user is created correctly.
Function register_new in which a new user is created ('temp_data' is a dict from 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)

,here's the registration.backend register function, that creates new user :

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

Traceback :

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 '[email protected]' for key 'username'")

I've googled for solutions and found many different including deleting/syncing tables, catching the IntegrityError in different places, changing decoding fields for table columns (I've tried setting to utf8_bin but no results). How to fix this problem ?

Table structure :

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

I've found this ticket at django docs :
http://code.djangoproject.com/ticket/3083
But there should be 2 models created at the same time. In my case nothing like this takes place I guess :/

UPDATE
Model :

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

方圜几里 2024-09-15 20:29:59

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

import MySQLdb

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

I'd catch MySQLdb error in this init file of registration backend, since it is first to cause problems :

import MySQLdb

(...)
    new_user = None
    try:    
        new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
    except MySQLdb.IntegrityError:
        pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文