django - 重复键值在保存 ModelForm 时违反了唯一约束

标签 django postgresql python-3.x database-design modelform

我的观点.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})

我的模型.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  

我的表格.py

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ['rewardpoints']

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password']

在提交 POST 请求时,它给了我:

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。

我什至尝试过更改数据库,运行 manage.py flush 但仍然没有成功。请给我线索。

这些是 Postgres 表:

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

最佳答案

有一个单独的表 users_userprofile 的想法可能是允许单个用户有多个条目。

(否则,如果每个用户只能有一个属性 rewardpoints,您只需将列添加到表 auth_user 并删除表 users_userprofile。)

实际的实现与这个想法相矛盾。您对 users_userprofile.user_id 有一个 UNIQUE 约束,这没有意义:

"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)

它会导致错误,可能应该被删除。

关于django - 重复键值在保存 ModelForm 时违反了唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28615208/

相关文章:

python-3.x - 使用过去可以通过 pip 安装但现在不能安装的库 (ocrodjvu)?

django - 通过模板使用 django 管理 pdf 并作为电子邮件附件发送

python - Pandas dataframe.query 到 SQL 'LIKE' 而不使用引擎 ='python'

django - Python:如何执行生成的代码?

python - "Unsupported hash type"错误 w/Python 2.6.5 和 django 框架

django - 使用 celery 更新 Django 模型字段时避免递归 save()

PostgreSQL 添加基于数据递增的 id 列

PostgreSQL 基于范围数字字段的唯一索引

python - 如何在 django 中对每个应用程序的用户进行身份验证

postgresql - 加载具有依赖关系的 Postgres 函数