Bruno Kalil Medeiros
Bruno Kalil Medeiros

Reputation: 31

IntegrityError: UNIQUE constraint failed: users_customuser.email

I'm a beginner at Django and this is my first project without a book or tutorial. I started my project with a Custom User class, base on AbstractUser. After that, I used the third-party package django-allauth to handle user registration flow, and it all worked fine. Users could only sign up and login with their email and username was not required as expected.

The problem started when I changed the sign up form in the django-allauth configs. In this new form I added some custom fields when the user signed up, but that gave me this error that I can't fix. One important thing is that the new users are created, even though I keep getting this error.

I've read a lot of question on the same issue but none helped me to fix my problem.

Edit with new field

Here is my 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', ]

My 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',)

And my 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)

Also, I checked the database and there isn't any email duplicated.

EDIT

Since I'm using django-allauth I think this code could help. 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'

Edit with new error The new error message

     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

Upvotes: 0

Views: 2762

Answers (2)

Bruno Kalil Medeiros
Bruno Kalil Medeiros

Reputation: 31

Ok, after some research I managed to solve my problem

The problem was in my CustomUserCreationForm. Since I'm using django-allauth for authentication, I should add just additional fields to the creation form and let django-allauth handle the email and password fields. So by deleting the email from the Meta class I could solve the IntegrityError that happened on the user's email.

Now my CustomUserCreationForm look like this:

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

Upvotes: 3

ino
ino

Reputation: 1125

Write it like this:

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

Upvotes: 1

Related Questions