重复键值在保存 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, 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})

我的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  

我的forms.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

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

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

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

"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)

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