Suraj Ingle
Suraj Ingle

Reputation: 412

Why am I receiving IntegrityError (1062, "Duplicate entry '' for key 'username'")?

I am receiving the following error (1062, "Duplicate entry '' for key 'username'") even though I haven't provided a username field at all.

I am trying to save the updated info of the user in its existing Account table.

Can you please help me understand the problem? The following are the details and code snippets. Thank you for your time in advance.

Error:

Request URL:    http://127.0.0.1:8000/profile/profileUpdate/
Django Version: 3.0.2
Exception Type: IntegrityError
Exception Value:    
(1062, "Duplicate entry '' for key 'username'")
Exception Location: C:\Users\hp\Envs\test\lib\site-packages\MySQLdb\connections.py in query, line 239
Python Executable:  C:\Users\hp\Envs\test\Scripts\python.exe
Python Version: 3.7.3

froms.py:

class ProfileUpdateForm(forms.ModelForm):

    class Meta:
        model = Account 
        fields = ('image', 'phone', 'guardianPhone', 'parrentPhone', 'emergencyPhone', 'address1', 'address2')

models.py:

class Account(AbstractBaseUser):
    username     = models.CharField(max_length = 50, unique= True)
    email        = models.EmailField(verbose_name = "email", max_length = 50, unique=True)
    image        = models.ImageField(upload_to = "pics/", default = "user/noimg")
    dateTime_joined  = models.DateTimeField(verbose_name="date joined", auto_now_add = True)
    is_admin     = models.BooleanField(default=False)
    is_staff     = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active    = models.BooleanField(default=True)

    first_login  =  models.BooleanField(default=True)
    room         = models.CharField(max_length = 10 , default = "unAssigned")
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone        = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
    #phone        = PhoneNumberField(null=False, unique = True)
    guardianPhone= models.CharField(validators=[phone_regex], max_length=17, blank=True)
    parrentPhone = models.CharField(validators=[phone_regex], max_length=17, blank=True)
    emergencyPhone= models.CharField(validators=[phone_regex], max_length=17, blank=True)

    address1 = models.CharField(max_length = 200, blank=True)
    address2 = models.CharField(max_length = 200, blank=True)

views.py :

def profileUpdate(request):
    context = {}
    if request.POST:
        form = ProfileUpdateForm(request.POST)
        if form.is_valid():
            form.save()
            user = request.user

            return redirect('../../dashboard/')
        else: 
            context['profile_form'] = form
    else:
        form = ProfileUpdateForm()
        context['profile_form'] = form
    return render(request, 'profileUpdate.html', context)

Upvotes: 0

Views: 2903

Answers (1)

Charnel
Charnel

Reputation: 4432

This happens because you set unique constraint on username field:

models.CharField(max_length = 50, unique= True)

Error is saying that you already have a record in DB with the username of zero length. You should or provide really unique name with your logic or generate a default unique name by adding default argument to this field:

models.CharField(max_length = 50, unique= True, default=some_callable)

, where callable is a method that provides unique names by default if non was provided during object creation with form. This may be a callable with some randome names generation.

Another option is to use pre_save signal with setting username by default to something like user.username = f'user_{hash_of_something}

Upvotes: 1

Related Questions