保存ModelForm时,重复键值违反唯一约束

时间:2015-02-19 19:29:49

标签: django postgresql python-3.x database-design 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})

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']

在提交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

1 个答案:

答案 0 :(得分:2)

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

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

实际执行与这一想法相矛盾。您对UNIQUEusers_userprofile.user_id约束,这没有意义:

"users_userprofile_user_id_key" UNIQUE CONSTRAINT, btree (user_id)

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