Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.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中的Users.username错误_Django_Django Models_Django Forms_Django Views - Fatal编程技术网

唯一约束失败:Django中的Users.username错误

唯一约束失败:Django中的Users.username错误,django,django-models,django-forms,django-views,Django,Django Models,Django Forms,Django Views,由于一些未知的原因,我面临着这个错误 我已经搜索了一些可能的错误,但是我尝试过的那些错误不起作用 我尝试了user=form.save(commit=False)也许它可以工作,但没有积极的结果 错误日志: Environment: Request Method: POST Request URL: http://localhost:8000/accounts/register-result Django Version: 3.1.2 Python Version: 3.7.3 Insta

由于一些未知的原因,我面临着这个错误

我已经搜索了一些可能的错误,但是我尝试过的那些错误不起作用

我尝试了
user=form.save(commit=False)
也许它可以工作,但没有积极的结果

错误日志:

Environment:


Request Method: POST
Request URL: http://localhost:8000/accounts/register-result

Django Version: 3.1.2
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'apps.accounts',
 'apps.result']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'apps.result.middleware.LoginRequiredMiddleware']



Traceback (most recent call last):
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (UNIQUE constraint failed: Users.username) was the direct cause of the following exception:
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\apps\accounts\views.py", line 32, in register_school
    user = User.objects.create_user(username=username,email=email,password=password)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\models.py", line 146, in create_user
    return self._create_user(username, email, password, **extra_fields)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\models.py", line 140, in _create_user
    user.save(using=self._db)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 754, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base
    force_update, using, update_fields,
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 895, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
    using=using, raw=raw,
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\query.py", line 1254, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\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:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /accounts/register-result
Exception Value: UNIQUE constraint failed: Users.username
观点:

def register_school(request):
if request.method == 'POST':
    form = SchoolRegistrationForm(request.POST)
    if form.is_valid():
        cleaned = form.cleaned_data
        username = cleaned['username']
        password = cleaned['password']
        email = cleaned['email']
        school_name = cleaned['school_name']
        address = cleaned['address']
        user = User.objects.create_user(username=username,email=email,password=password)
        user.usertype = 'result'
        user = form.save(commit=False)
        user.save()
        school = School(user=user,
                        name=school_name,
                        address=address,
                        )
        school.save()
        return redirect(reverse('registration-complete', kwargs={'username': username}))
else:
    form = SchoolRegistrationForm
    return render(request, 'registration.html', {'form': form})
表格:


从代码流来看,这可能是问题所在:

# first you call user variable
user = User.objects.create_user(username=username,email=email,password=password)
# set uset attribute
user.usertype = 'result'
# you override `user` variable
user = form.save(commit=False)
# now trying to save the form so result in trying to create another record with the same data
user.save()

# failed because username have unique constrain 

您不需要设置user=form.save(commit=False),因为我看不到您在其他任何地方使用
user
variable

调用表单。错误只是说您键入的
username
已经存在于数据库中。要解决此问题,请为
学校注册表单
中的
用户名
字段添加表单验证。另外,
form.save(commit=False)
无论如何都不会工作,因为表单不是
ModelForm

只有基于模型的表单
ModelForm
具有内置的。对于基于
表单的表单
,必须创建一个模态对象并保存该实例

def注册学校(请求):
如果request.method==“POST”:
表单=学校注册表单(request.POST)
如果form.is_有效():
cleaned=form.cleaned\u数据
# https://docs.djangoproject.com/en/3.1/topics/auth/default/#creating-使用者
用户名=已清除['username']
密码=已清除['password']
电子邮件=已清理['email']
user=user.objects.create\u user(
用户名=用户名,
电子邮件=电子邮件,
密码=密码
)
user.usertype='result'
user.save()
#创建模型实例并保存()
学校名称=已清理[“学校名称”]
地址=已清理[“地址”]
学校(
用户=用户,
名称=学校名称,
地址,
)
学校。保存()
返回重定向(反向('registration-complete',kwargs={'username':username}))
其他:
表格=学校注册表格()
返回呈现(请求'registration.html',{'form':form})
将验证添加到
学校注册表单
表单中的
用户名
字段。这将检查用户名是否已经存在,并在视图中创建
用户时在表单中引发验证错误,而不是模式错误

#forms.py
#进口
从django.core.exceptions导入ValidationError
从django.contrib.auth导入get\u user\u模型
班级学校注册表(forms.Form):
username=forms.CharField(label='username')
#其他领域
# https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-特定字段属性
def clean_用户名(自我):
数据=自清理的数据['username']
用户\模型=获取\用户\模型()
如果用户\u model.objects.filter(用户名=数据).exists():
引发ValidationError(“用户名已存在”)
#始终返回一个值以用作新清理的数据,即使
#这个方法没有改变它。
返回数据

学校注册表单
表单中的这些字段是否基于您的
用户
模型?您是否有自定义的
用户
?错误仅表示您键入的
用户名
已存在于数据库中。另外,
form.save(commit=False)
无论如何都不会工作,因为
表单
不是
模型表单
。非常感谢,先生,您的解决方案工作得非常好。
# first you call user variable
user = User.objects.create_user(username=username,email=email,password=password)
# set uset attribute
user.usertype = 'result'
# you override `user` variable
user = form.save(commit=False)
# now trying to save the form so result in trying to create another record with the same data
user.save()

# failed because username have unique constrain