IntegrityError-unique constraint failed

Dear Django developers

Thank you for creating such an amazing framework!

My problem is the following:

I have created a Custom User model which inherits from AbstractUser. Furthermore I have created a custom user manager which inherits from UserManager.

When trying to register a new user, I get an integrity error stating unique constraint failed for my custom user model’s username. The thing is, I have defined the username field as comp_name. So when I try to register a new user nothing gets saved and I get thrown the Integrity Error

The only user saved in my database is the superuser which has a comp_name of ‘fabian’

Here is my models.py file:

from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
from django.conf import settings
# Create your models here.




class CustomUserManager(UserManager):
    def create_superuser(self, comp_name, email=None, password=None, **extra_fields):
        if not comp_name:
            raise ValueError("User must have a comp_name")
        if not email:
            raise ValueError("User must have an email")
        if not password:
            raise ValueError("User must have a password")

        user = self.model(
            email=self.normalize_email(email)
        )
        user.comp_name = comp_name
        user.set_password(password)
        user.is_admin = True
        user.is_staff = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractUser):
    business_choices = (
        ('Manufacturers', 'Manufacturers'),
        ('Service Providers', 'Service Providers'),
        ('Retailers', 'Retailers'),
        ('Wholesalers', 'Wholesalers'),
    )
    comp_name = models.CharField(max_length=30, primary_key=True, verbose_name="Company Name", default="test")
    reg_no = models.IntegerField(default=123456789, verbose_name="Registration Number")
    contact = models.IntegerField(default=12345678, verbose_name="Contact")
    website = models.CharField(max_length=20, default="basileia.com", verbose_name="Website")
    location = models.CharField(max_length=70, verbose_name="Location")
    pic = models.ImageField(null=True, blank=True, verbose_name="Profile Picture")
    doi = models.DateField(auto_now=False, blank=True, default="1995-07-21", verbose_name="Date of Incorporation")
    type_of_business = models.CharField(max_length=20, choices=business_choices, default='Manufacturers', verbose_name="Type of business")
    USERNAME_FIELD = 'comp_name'
    objects = CustomUserManager()

    @staticmethod
    def has_perm(perm, obj=None):
        # "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    @staticmethod
    def has_module_perms(app_label):
        # "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    def __str__(self):
        return self.comp_name

    def get_username(self):
        return self.comp_name

Here is my admin.py file:

from django.contrib import admin
from dashboard.models import CustomUser
from django.contrib.auth.admin import UserAdmin
from forms import CustomUserCreationForm, CustomUserChangeForm
# Register your models here.


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['comp_name', 'reg_no', 'contact', 'email',
                    'website', 'location', 'doi']



admin.site.register(CustomUser, CustomUserAdmin)

In my settings file I have the AUTH_USER_MODEL set to my custom model in this case 'dashboard.CustomUser'

In my forms.py file:

from django.contrib.auth.forms import AuthenticationForm, UserChangeForm, UserCreationForm
from dashboard.models import CustomUser


class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ['comp_name', 'reg_no', 'email',
                  'contact', 'doi', 'location', 'website',
                  'password1', 'password2', 'type_of_business', 'pic']

    def save(self, commit=True):
        user = super(CustomUserCreationForm, self).save(commit=False)
        user.comp_name = self.cleaned_data['comp_name']
        user.reg_no = self.cleaned_data['reg_no']
        user.email = self.cleaned_data['email']
        user.contact = self.cleaned_data['contact']
        user.doi = self.cleaned_data['doi']
        user.location = self.cleaned_data['location']
        user.website = self.cleaned_data['website']
        user.type_of_business = self.cleaned_data['type_of_business']
        user.pic = self.cleaned_data['pic']
        if commit:
            user.save()
        return user



class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = '__all__'


class CustomLoginForm(AuthenticationForm):
    pass

In my views.py file:

from django.shortcuts import render, redirect
from django.contrib.auth.views import LoginView
from forms import CustomLoginForm, CustomUserCreationForm


# Create your views here.


class LoginPageView(LoginView):
    redirect_authenticated_user = True
    authentication_form = CustomLoginForm
    template_name = "registration/login.html"


def SignUpPageView(request):
    form = CustomUserCreationForm()

    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
        elif not form.is_valid():
            print('Form is not valid')
            print(form.errors)

    context = {'form': form}
    return render(request, "registration/signup.html", context)


def DashboardPageView(request):
    return render(request, "dashboard/index.html")


def ProfilePageView(request):
    return render(request, "dashboard/profilepage.html")


def NotificationsPageView(request):
    return render(request, "dashboard/notifications.html")

And finally the full error pasted here:

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

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Admin user\PycharmProjects\OfficialGetBusyWebsite\dashboard\views.py", line 21, in SignUpPageView
    form.save()
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\contrib\auth\forms.py", line 131, in save
    user.save()
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\base.py", line 763, in save_base
    updated = self._save_table(
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
    return manager._insert(
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
    cursor.execute(sql, params)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\ProgramData\Anaconda3\envs\OfficialGetBusyWebsite\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: dashboard_customuser.username

Thanks in advance for all your help!

and HAPPY NEW YEAR!!!

Notice the specific field that it’s complaining about:

Then read: Customizing authentication in Django | Django documentation | Django

1 Like