保存ModelForm时重复的键值违反了唯一约束 [英] Duplicate key value violates unique constraint while saving ModelForm
问题描述
我的views.py
class UserProfileFormView(View):
def post(self,request,* args ,** kwargs):
userform = UserForm(request.POST,前缀='用户')
userprofileform = UserProfileForm(request.POST,前缀='userprofiles')
如果userform.is_valid ()和userprofileform.is_valid():
new_user = userform.save()
new_userprofile = userprofileform.save(commit = False)
new_userprofile.user = new_user
new_userprofile.save ()####错误在这里
return HttpResponseRedirect(reverse('users:welcome'))
else:
userform = UserForm(prefix ='users')
userprofileform = UserProfileForm(prefix ='userprofiles')
return render(request,'users / signup.html',{'user_form':userform,'userprofile_form':userprofileform})
def get(自身,请求,* args,** kwargs):
userform = UserForm(prefix ='user s')
userprofileform = UserProfileForm(prefix ='userprofiles')
return render(request,'users / signup.html',{'user_form':userform,'userprofile_form':userprofileform})
我的模型。py
class UserProfile(models.Model):
user = models.OneToOneField(User,verbose_name =用户详细信息)
rewardpoints = models.IntegerField( rewardpoints,默认= 0)
def __str __(self):
返回%s的个人资料%self.user.username
我的表格.py
class UserProfileForm(ModelForm):
class Meta:
模型= UserProfile
字段= ['rewardpoints']
类UserForm(ModelForm):
类元:
模型=用户
字段= ['用户名','密码']
同时提交 POST
请求,它给了我:
重复键值违反唯一约束 users_userprofile_user_id_key
详细信息:键(user_id)=(1)已存在。
Django-1.7,PostgreSQL 9.3.6。
我什至尝试更改数据库,运行 manage.py flush
,但还是没有运气。请给我线索。
这些是Postgres表:
auth_user
列|类型修饰符
-------------- + -------------------------- + --- -------------------------------------------------- ---
id |整数|不为空默认nextval(’auth_user_id_seq’:: regclass)
密码|角色变化(128)|不为空
last_login |带时区的时间戳记|不为空
is_superuser |布尔值|不为空
用户名|角色变化(30)|不为空
first_name |角色变化(30)|不为空
last_name |角色变化(30)|不为空
电子邮件|角色变化(75)|不为空
is_staff |布尔值|不为空
is_active |布尔值|不为空
date_joined |带时区的时间戳记|不为空
索引:
auth_user_pkey主键,btree(id)
auth_user_username_key唯一约束,btree(用户名)
auth_user_username_615a2337ed0898d6_like btree(用户名varchar_pattern_ops)通过引用$ b:
表 account_emailaddress 约束 account_emailaddress_user_id_43dc87ab5814030c_fk_auth_user_id 外键(USER_ID)参考AUTH_USER(ID)DEFERRABLE INITIALLY DEFERRED
表 auth_user_groups 约束 auth_user_groups_user_id_365abed9418f0260_fk_auth_user_id 外键(USER_ID)参考AUTH_USER( ID)DEFERRABLE INITIALLY DEFERRED
表 auth_user_user_permissions 约束 auth_user_user_permiss_user_id_50dbc406b985ecc5_fk_auth_user_id 外键(USER_ID)参考AUTH_USER(ID)DEFERRABLE INITIALLY DEFERRED
表 authtoken_token 约束 authtoken_token_user_id_1496385360418da0_fk_auth_user_id 外键(USER_ID)参考AUTH_USER( id)最初应递延d
表 django_admin_log 约束 django_admin_log_user_id_1f9a3ebc14adbded_fk_auth_user_id 外键(USER_ID)参考AUTH_USER(ID)DEFERRABLE INITIALLY DEFERRED
表 users_userprofile 约束 users_userprofile_user_id_35e6cb6eb864c8ec_fk_auth_user_id 外键(USER_ID)参考AUTH_USER(ID)DEFERRABLE INITIALLY延迟
users_userprofile
列|类型修饰符
-------------- + --------- + -------------------- --------------------------------------------
id |整数|不为空默认nextval(’users_userprofile_id_seq’:: regclass)
奖励积分|整数|不为空
user_id |整数|不为null
索引:
users_userprofile_pkey主键,btree(id)
users_userprofile_user_id_key唯一约束,btree(user_id)
外键约束:
users_userprofile_user_id_35e6cb6eb864c8ec_fk_auth_user_id FOREIGN KEY(user_id)参考auth_user(id)最初被延迟
使用单独的表 users_userprofile
的想法可能是允许单个用户进行多个输入。
(否则,如果每个用户只有一个属性 rewardpoints
,则只需将该列添加到表 auth_user
并删除表 users_userprofile
。)
实际实现与此想法相矛盾。您在 users_userprofile.user_id
上具有 UNIQUE
约束,这没有任何意义:
users_userprofile_user_id_key唯一约束,btree(user_id)
它会导致错误,应该将其删除。
My views.py
class UserProfileFormView(View):
def post(self, request, *args, **kwargs):
userform = UserForm(request.POST, prefix='users')
userprofileform = UserProfileForm(request.POST, prefix='userprofiles')
if userform.is_valid() and userprofileform.is_valid():
new_user = userform.save()
new_userprofile = userprofileform.save(commit=False)
new_userprofile.user = new_user
new_userprofile.save() #### Error is here
return HttpResponseRedirect(reverse('users:welcome'))
else:
userform = UserForm(prefix='users')
userprofileform = UserProfileForm(prefix='userprofiles')
return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})
def get(self, request, *args, **kwargs):
userform = UserForm(prefix='users')
userprofileform = UserProfileForm(prefix='userprofiles')
return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})
my models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name="user details")
rewardpoints = models.IntegerField("rewardpoints", default=0)
def __str__(self):
return "%s's profile" % self.user.username
my forms.py
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['rewardpoints']
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
While submitting the POST
request, it gives me:
duplicate key value violates unique constraint "users_userprofile_user_id_key" DETAIL: Key (user_id)=(1) already exists.
Django-1.7, PostgreSQL 9.3.6.
I have even tried changing the database, running manage.py flush
but still no luck. Please give me leads.
These are the Postgres tables:
auth_user
Column | Type | Modifiers
--------------+--------------------------+--------------------------------------------------------
id | integer | not null default nextval('auth_user_id_seq'::regclass)
password | character varying(128) | not null
last_login | timestamp with time zone | not null
is_superuser | boolean | not null
username | character varying(30) | not null
first_name | character varying(30) | not null
last_name | character varying(30) | not null
email | character varying(75) | not null
is_staff | boolean | not null
is_active | boolean | not null
date_joined | timestamp with time zone | not null
Indexes:
"auth_user_pkey" PRIMARY KEY, btree (id)
"auth_user_username_key" UNIQUE CONSTRAINT, btree (username)
"auth_user_username_615a2337ed0898d6_like" btree (username varchar_pattern_ops)
Referenced by:
TABLE "account_emailaddress" CONSTRAINT "account_emailaddress_user_id_43dc87ab5814030c_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
TABLE "auth_user_groups" CONSTRAINT "auth_user_groups_user_id_365abed9418f0260_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
TABLE "auth_user_user_permissions" CONSTRAINT "auth_user_user_permiss_user_id_50dbc406b985ecc5_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
TABLE "authtoken_token" CONSTRAINT "authtoken_token_user_id_1496385360418da0_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
TABLE "django_admin_log" CONSTRAINT "django_admin_log_user_id_1f9a3ebc14adbded_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
TABLE "users_userprofile" CONSTRAINT "users_userprofile_user_id_35e6cb6eb864c8ec_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
users_userprofile
Column | Type | Modifiers
--------------+---------+----------------------------------------------------------------
id | integer | not null default nextval('users_userprofile_id_seq'::regclass)
rewardpoints | integer | not null
user_id | integer | not null
Indexes:
"users_userprofile_pkey" PRIMARY KEY, btree (id)
"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)
Foreign-key constraints:
"users_userprofile_user_id_35e6cb6eb864c8ec_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
The idea of having a separate table users_userprofile
is probably to allow multiple entries for a single user.
(Else, if there can only be a single attribute rewardpoints
per user, you would just add the column to the table auth_user
and drop the table users_userprofile
.)
The actual implementation contradicts this idea. You have a UNIQUE
constraint on users_userprofile.user_id
, which does not make sense:
"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)
It causes the error and should probably be removed.
这篇关于保存ModelForm时重复的键值违反了唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!