我收到以下错误(1062,"密钥'用户名'的重复条目''"( 即使我根本没有提供用户名字段。
我正在尝试将用户的更新信息保存在其现有的帐户表中。
你能帮我理解这个问题吗? 以下是详细信息和代码片段。提前感谢您抽出宝贵时间。
错误:
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:UsershpEnvstestlibsite-packagesMySQLdbconnections.py in query, line 239
Python Executable: C:UsershpEnvstestScriptspython.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)
发生这种情况是因为您在username
字段上设置了unique
约束:
models.CharField(max_length = 50, unique= True)
错误是说您在数据库中已经有一条用户名为零长度的记录。 您应该或为您的逻辑提供真正唯一的名称,或者通过向此字段添加默认参数来生成默认的唯一名称:
models.CharField(max_length = 50, unique= True, default=some_callable)
,其中 callable 是一种方法,如果在使用 form 创建对象期间未提供 non,则默认情况下提供唯一名称。这可能是一些随机名称生成的可调用对象。
另一种选择是使用pre_save信号,默认情况下将用户名设置为类似user.username = f'user_{hash_of_something}