Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 为什么我会收到IntegrityError(1062,“重复输入”和“重复输入”作为键和用户名)?_Django_Forms_Django Custom User - Fatal编程技术网

Django 为什么我会收到IntegrityError(1062,“重复输入”和“重复输入”作为键和用户名)?

Django 为什么我会收到IntegrityError(1062,“重复输入”和“重复输入”作为键和用户名)?,django,forms,django-custom-user,Django,Forms,Django Custom User,我收到以下错误(1062,“用户名”项的“重复条目”) 即使我根本没有提供用户名字段 我正在尝试将用户的更新信息保存在其现有帐户表中 你能帮我理解这个问题吗? 以下是详细信息和代码片段。提前感谢您抽出时间 错误: Request URL: http://127.0.0.1:8000/profile/profileUpdate/ Django Version: 3.0.2 Exception Type: IntegrityError Exception Value: (1062, "

我收到以下错误(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:\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)


这是因为您在
用户名
字段上设置了
唯一
约束:

models.CharField(max_length = 50, unique= True)
错误是您在DB中已经有一条用户名为零的记录。 您应该在逻辑中使用或提供真正唯一的名称,或者通过向此字段添加默认参数来生成默认唯一名称:

models.CharField(max_length = 50, unique= True, default=some_callable)
,其中callable是一个默认情况下提供唯一名称的方法,如果在使用表单创建对象期间提供了non。这可能是一个可调用的随机名称生成


另一个选项是使用signal,默认情况下将username设置为类似于
user.username=f'user\uu{hash\u of_something}

,但我没有以上述形式提供user.username属性。那么为什么要调用它呢?@user9304976,即使您没有显式地提供并不意味着数据库中不会存储任何内容的内容。此字段是charfield,因此如果没有值,它将把空字符串存储到DB中。您已经有这样一个记录-它引发了一个错误,因为两个空字符串相等,因此不能唯一。在views.py中创建表单对象时,通过将
instance=request.user
作为第二个参数传递给来解决此问题。。。。