0

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)

Suraj Ingle
  • 372
  • 4
  • 18

1 Answers1

1

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}

Charnel
  • 4,222
  • 2
  • 16
  • 28
  • but I am not providing the user.username attribute in the above mentioned form. then why is it being called at all? – Suraj Ingle Feb 14 '20 at 12:07
  • @user9304976 even if you are not explicitly providing something that doesn't mean that nothing will be stored in DB. This field is a charfield so without a value it will store empty string into DB. You already have such a record - that raised an error because two empty string are equal and thus can't be unique. – Charnel Feb 14 '20 at 12:31
  • it got solved by passing `instance = request.user` as 2nd argument to while creating the form object in views.py.... – Suraj Ingle Feb 15 '20 at 02:55