IntegrityError: UNIQUE constraint failed: users_customuser.email

IntegrityError: UNIQUE constraint failed: users_customuser.email

我是 Django 的初学者,这是我第一个没有书籍或教程的项目。我以基于 AbstractUser 的自定义用户 class 开始了我的项目。之后,我使用第三方包django-allauth来处理用户注册流程,一切正常。用户只能使用他们的电子邮件注册和登录,并且不需要用户名。

当我更改 django-allauth 配置中的注册表单时,问题开始了。在这个新表单中,我在用户注册时添加了一些自定义字段,但这给了我这个我无法修复的错误。 一件重要的事情是创建了新用户,尽管我一直收到此错误。

我已经阅读了很多关于同一问题的问题,但 none 帮助我解决了我的问题。

用新字段编辑

这是我的models.py:

class CustomUser(AbstractUser):
  username = models.CharField(max_length=100, unique=True, null=True)
  email = models.EmailField(verbose_name="Email", null=True, unique=True, max_length=250)
  first_name = models.CharField(verbose_name="Nome", max_length=100, null=True)
  last_name = models.CharField(verbose_name="Sobrenome", max_length=250, null=True)

USERNAME_FIELD = 'email' 
REQUIRED_FIELDS = ['first_name', 'last_name', ]

我的forms.py:

class CustomUserCreationForm(UserCreationForm):

  class Meta:
        model = get_user_model()
        fields = ('email', 'first_name', 'last_name', 'major', 'university',)

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'major', 'university',)

还有我的admin.py:

class CustomUserAdmin(UserAdmin):
  add_form = CustomUserCreationForm
  form = CustomUserChangeForm
  model = CustomUser
  list_display = ['full_name', 'email', 'major', 'university', ]
  #fieldsets add fields to the change form and add_fieldsets to the creation form
  fieldsets = UserAdmin.fieldsets + (
      (None, {'fields': ('major', 'university',)}),
  )
  add_fieldsets = (
      (None, {
          'classes': ('wide',),
          'fields': ('email', 'username', 'first_name', 'last_name', 'major', 'university'),
      }),
  )
ordering = ('email',)

admin.site.register(CustomUser, CustomUserAdmin)

此外,我检查了数据库,没有任何重复的电子邮件。

编辑

因为我使用的是 django-allauth,所以我认为这段代码可以提供帮助。 settings.py:

#Django allauth settings
ACCOUNT_EMAIL_REQUIRED = True #Email is required when signing up
ACCOUNT_AUTHENTICATION_METHOD = "email" #Users can only log in using their 
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_LOGOUT_REDIRECT = 'home'
LOGIN_REDIRECT_URL = 'home'
ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.CustomUserCreationForm'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

编辑出现新错误 新的错误信息

     Internal Server Error: /accounts/signup/
Traceback (most recent call last):
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: users_customuser.email

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\views.py", line 215, in dispatch
    return super(SignupView, self).dispatch(request, *args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\views.py", line 78, in dispatch
    response = super(RedirectAuthenticatedUserMixin,
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\views.py", line 191, in dispatch
    return super(CloseableSignupMixin, self).dispatch(request,
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\views.py", line 104, in post
    response = self.form_valid(form)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\views.py", line 231, in form_valid
    self.user = form.save(self.request)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\forms.py", line 405, in save
    self.custom_signup(request, user)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\allauth\account\forms.py", line 359, in custom_signup
    custom_form.save(user)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\contrib\auth\forms.py", line 128, in save
    user.save()
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save
    super().save(*args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\base.py", line 886, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\base.py", line 923, in _do_insert
    return manager._insert(
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\models\sql\compiler.py", line 1377, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Bruno\.virtualenvs\Sophia-owJCV_9p\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email
[21/Aug/2020 11:08:00] "POST /accounts/signup/ HTTP/1.1" 500 214904

Database before creating first user

Database after creating first user

这样写:

email = models.EmailField(verbose_name="Email", null=True, unique=True, max_length=100)

好的,经过一些研究我设法解决了我的问题

问题出在我的 CustomUserCreationForm 中。由于我使用 django-allauth 进行身份验证,因此我应该在创建表单中添加额外的字段并让 django-allauth 处理电子邮件和密码字段。 因此,通过从 Meta class 中删除电子邮件,我可以解决用户电子邮件中发生的 IntegrityError。

现在我的 CustomUserCreationForm 看起来像这样:

        model = CustomUser
        fields = ('first_name', 'last_name', 'date_of_birth', )```